I have the two following models and DbContext:
public class TestDbContext : DbContext
{
public IDbSet People { get; set; }
Try something like this :
using (TestDbContext context = new TestDbContext())
{
foreach (Person person in People)
{
if (!(context.People.Any(p => p.ID == person.ID)))
context.People.Add(person);
else
{
context.People.Attach(person);
context.Entry<Person>(person).State = System.Data.EntityState.Modified;
}
context.SaveChanges();
}
foreach (Car caar in Cars)
{
if (!(context.Cars.Any(c => c.ID == caar.ID)))
context.Cars.Add(caar);
else
{
context.Cars.Attach(caar);
context.Entry<Car>(caar).State = System.Data.EntityState.Modified;
}
context.SaveChanges();
}
}
I think your error is due to the context.SaveChanges
placements (and partialy your architecture). Consider using a dedicated method (a basic CRUD for instance) for each operation on your DB via Entity Framework. Hope this helps.
Edit : With a CRUD approch :
public class PersonManager // CRUD
{
public void Create(Person person)
{
using (TestDbContext context = new TestDbContext())
{
context.Person.Add(person);
context.SaveChanges();
}
}
public void Update(Person person)
{
using (TestDbContext context = new TestDbContext())
{
context.Person.Attach(person);
context.Entry(person).State = System.Data.EntityState.Modified;
context.SaveChanges();
}
}
}
You could also make this class static
in order to fit to your architecture.
I believe this is a problem of independent vs foreign key association. You are using independent association at the moment and the relation between car and person is actually managed by separate entry object which has its own state (to access this object you must use ObjectContext API). Setting the car's entity entry to modified state will not change the state of the entry for the relation! The simple solution is to use foreign key association instead which means adding new Guid PersonId
property to your car and map it as foreign key property for Person
navigation property.
If you insist on using independent associations you should change relations only on attached entities otherwise you will had a strong headache with tracking those changes and setting all required entries with correct state. It should be enough to create objects, attach them to context and only after that set the owner of the car - hopefully it will be tracked as a change.