0

I would like to be able to locate newly-added EF Core entities without having to do a DbContext.SaveChanges() first (my desire stems from the fact that I'm adding entities recursively, and need access to newly-added entities in the child entities, and I'm looking to minimize database updates).

To put this in context, in the following pseudo-code entity2 will be null unless the commented line is uncommented:

var entity1 = DbContext.Assemblies
            .FirstOrDefault( x => x.Name.Equals( assemName, StringComparison.OrdinalIgnoreCase ) );

if( entity1 == null )
{
    entity1 = new AssemblyDb()
    {
        Name = assemName,
    };

    DbContext.Assemblies.Add( retVal );

    //DbContext.SaveChanges();
}

var entity2 = dbUpdater.DbContext.Assemblies
            .FirstOrDefault( x => x.Name.Equals( assemName, StringComparison.OrdinalIgnoreCase ) );

There is an SO discussion from years ago about this for Entity Framework here. I'm interested to see if there's a simple way of achieving the same end under EF Core.

Mark Olbert
  • 6,584
  • 9
  • 35
  • 69

1 Answers1

2

You can access any entries that the ChangeTracker is keeping track of, by doing something like:

    foreach (EntityEntry entry in context.ChangeTracker.Entries())
    {
         var entityObject = entry.Entity;
    }

Update:

Use Find() if possible.

The thing that's nice about Find is that it looks at the change tracker to see if there is already an object with that primary key in the local context and it will return it without querying the database.

DbContext.Find

Finds an entity with the given primary key values. If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database. Otherwise, a query is made to the database for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found, then null is returned.

Dennis VW
  • 2,977
  • 1
  • 15
  • 36
  • Thanx, Dennis. I can build an extension method based on that. Somewhat surprising that it isn’t part of EF Core, but you can’t have everything – Mark Olbert Sep 14 '19 at 21:40
  • @MarkOlbert while thinking about the problem I realized that EF Core does have a method that can query the context without querying the database. So I've updated my answer. – Dennis VW Sep 14 '19 at 22:14
  • Wow! Can't give you more than one upvote, but I really appreciate the diligence and follow-up. Have a virtual beverage of your choice on me! – Mark Olbert Sep 15 '19 at 00:53
  • A quick follow-up -- Find() "only" searches on the primary key. That's sufficient in many cases, but in mine I need to search on property values. So I'll go the roll-your-own route. – Mark Olbert Sep 15 '19 at 00:56