There is already an object named in the database

it seems there is a problem in migration process, run add-migration command in “Package Manager Console”: Add-Migration Initial -IgnoreChanges do some changes, and then update database from “Initial” file: Update-Database -verbose Edit: -IgnoreChanges is in EF6 but not in EF Core, here’s a workaround: https://stackoverflow.com/a/43687656/495455

How do I stop Entity Framework from trying to save/insert child objects?

As far as I know, you have two options. Option 1) Null all the child objects, this will ensure EF not to add anything. It will also not delete anything from your database. Option 2) Set the child objects as detached from the context using the following code context.Entry(yourObject).State = EntityState.Detached Note that you can … Read more

ASP.NET MVC – Attaching an entity of type ‘MODELNAME’ failed because another entity of the same type already has the same primary key value

Problem SOLVED! Attach method could potentially help somebody but it wouldn’t help in this situation as the document was already being tracked while being loaded in Edit GET controller function. Attach would throw exactly the same error. The issue I encounter here was caused by function canUserAccessA() which loads the A entity before updating the … Read more

Entity Framework Code First – Advantages and disadvantages of Fluent Api vs Data Annotations [closed]

Everything what you can configure with DataAnnotations is also possible with the Fluent API. The reverse is not true. So, from the viewpoint of configuration options and flexibility the Fluent API is “better”. Configuration examples (for sure not a full list) which are possible in the Fluent API but not with DataAnnotations (as far as … Read more

Entity Framework code first unique column

In Entity Framework 6.1+ you can use this attribute on your model: [Index(IsUnique=true)] You can find it in this namespace: using System.ComponentModel.DataAnnotations.Schema; If your model field is a string, make sure it is not set to nvarchar(MAX) in SQL Server or you will see this error with Entity Framework Code First: Column ‘x’ in table … Read more

DbSet.Attach(entity) vs DbContext.Entry(entity).State = EntityState.Modified

When you do context.Entry(entity).State = EntityState.Modified;, you are not only attaching the entity to the DbContext, you are also marking the whole entity as dirty. This means that when you do context.SaveChanges(), EF will generate an update statement that will update all the fields of the entity. This is not always desired. On the other … Read more