There are several options here, I will list 3 of them:
Option 1: Using GraphDiff
* For this, Configuration.AutoDetectChangesEnabled
your context is set to true.
Just install GraphDiff with NuGet
Install-Package RefactorThis.GraphDiff
Then
using (var context = new Context()) { var customer = new Customer() { Id = 12503, Name = "Jhon Doe", City = new City() { Id = 8, Name = "abc" } }; context.UpdateGraph(customer, map => map.AssociatedEntity(p => p.City)); context.Configuration.AutoDetectChangesEnabled = true; context.SaveChanges(); }
Read more about GraphDiff here .
Option 2: Search and Edit
Search for your object using EF to track it in context. Then edit the properties.
* For this, Configuration.AutoDetectChangesEnabled
your context is set to true.
var customer = new Customer() { Id = 12503, Name = "Jhon Doe", City = new City() { Id = 8, Name = "abc" } }; using (var context = new Contexto()) { var customerFromDatabase = context.Customers .Include(x => x.City) .FirstOrDefault(x => x.Id == customer.Id); var cityFromDataBase = context.Cities.FirstOrDefault(x => x.Id == customer.City.Id); customerFromDatabase.Name = customer.Name; customerFromDatabase.City = cityFromDataBase; context.Configuration.AutoDetectChangesEnabled = true; context.SaveChanges(); }
Option 3: using a scalar property
In terms of performance, this is the best way, but it will prevent your class from having a database problem. Because you will need to create a scalar (primitive type) property to match the identifier.
* Thus, there is no need to set Configuration.AutoDetectChangesEnabled
to true. And also you will not need to make a query to the database to extract entities (since the first two parameters are yes, GraphDiff does this behind the scenes!).
var customer = new Customer() { Id = 12503, Name = "Jhon Doe", City_Id = 8, City = null }; using (var contexto = new Contexto()) { contexto.Entry(customer).State = EntityState.Modified; contexto.SaveChanges(); }