locked
Search on newly added objects before calling Savechanges ? RRS feed

  • Question

  • Hello !

    I have this code :

    dim nw as new Myobj1

    Myobj1.nr=1

    .....

    context.Mytables.add(Myobj1)

    dim I as integer

    I=context.mytables.where(Function(t) t.nr=1).count

    .....

    In the last instruction , I=0.

    How can I do that before calling context.savechanges , to search on newly added objects ?

    Thank you !

    Tuesday, October 14, 2014 1:55 PM

Answers

  • You could retrieve all new objects (with EntityState = Added) from the ChangeTracker.Entries collection of the DbContext:

    //VB.NET
    Dim newEntities = context.ChangeTracker.Entries(Of YourEntityType)().Where(Function(e) e.State = EntityState.Added)
    

    //C#:
    var newEntities = context.ChangeTracker.Entries<YourEntityType>().Where(e => e.State == EntityState.Added);

    Please remember to mark helpful posts as answer and/or helpful.

    • Proposed as answer by Fred Bao Wednesday, October 15, 2014 2:19 AM
    • Marked as answer by Fred Bao Friday, October 24, 2014 6:41 AM
    Tuesday, October 14, 2014 3:40 PM