The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

Without overriding EF track system, you can also Detach the ‘local’ entry and attach your updated entry before saving : // var local = _context.Set<YourEntity>() .Local .FirstOrDefault(entry => entry.Id.Equals(entryId)); // check if local is not null if (local != null) { // detach _context.Entry(local).State = EntityState.Detached; } // set Modified flag in your entry _context.Entry(entryToUpdate).State … Read more

Entity Framework select distinct name

Using lambda expression.. var result = EFContext.TestAddresses.Select(m => m.Name).Distinct(); Another variation using where, var result = EFContext.TestAddresses .Where(a => a.age > 10)//if you have any condition .Select(m => m.name).Distinct(); Another variation using sql like syntax var result = (from recordset in EFContext.TestAddresses .where(a => a.city = ‘NY’)//if you have any condition .select new { recordset.name … Read more

Entity Framework .Remove() vs. .DeleteObject()

It’s not generally correct that you can “remove an item from a database” with both methods. To be precise it is like so: ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It’s EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential … Read more

Can I generate script of a migration with EF code first and .net core

As per EF documentation you can use Script-Migration command. If you want to just script all the migrations you can simply call it from Package Manager console like that. If you want to just script the changes from the last migration you can call it like this: Script-Migration -From <PreviousMigration> -To <LastMigration> Be sure to … Read more

Entity Framework with NOLOCK

No, but you can start a transaction and set the isolation level to read uncommited. This essentially does the same as NOLOCK, but instead of doing it on a per table basis, it will do it for everything within the scope of the transaction. If that sounds like what you want, here’s how you could … Read more

How to re-create database for Entity Framework?

Follow below steps: 1) First go to Server Explorer in Visual Studio, check if the “.mdf” Data Connections for this project are connected, if so, right click and delete. 2 )Go to Solution Explorer, click show All Files icon. 3) Go to App_Data, right click and delete all “.mdf” files for this project. 4) Delete … Read more

Debug code-first Entity Framework migration codes

I know that EF Code First Migrations is relatively new tool but don’t forget about you are still in .NET. So you can use: if (System.Diagnostics.Debugger.IsAttached == false) { System.Diagnostics.Debugger.Launch(); } After that you can see your InnerException. Or you can use try…catch statement like this: Exception handling Entity Framework