I have the following models
Factory can have multiple Cars, A Car can have TypeA & TypeB
public class Factory
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int FactoryID {get;set;}
public ICollection<Car> Cars {get;set;}
}
public class Car
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CarID {get;set;}
public int FactoryID {get;set;}
public Factory Factory {get;set;}
//The Types
public TypeA TypeA {get;set;}
public TypeB TypeB {get;set;}
}
public class TypeA
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TypeAID {get;set;}
[Key, ForeignKey("Car")]
public int CarID {get;set;}
public Car Car {get;set;}
}
public class TypeB
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TypeBID {get;set;}
[Key, ForeignKey("Car")]
public int CarID {get;set;}
public Car Car {get;set;}
}
Which is shown in an EditorTemplate with the following
Factory factory = Factory factory = db.Factory.Where(f => f.FactoryID == 1)
.Include(f => f.Cars.Select(c => c.TypeA))
.Include(f => f.Cars.Select(c => c.TypeB)).FirstOrDefault();
I just post the model to view and so on and so forth. Then comes the time to post the data back to the model.
I have the following action, which is my post action.
public ActionResult FactoryEdit(Factory factory)
{
if(ModelState.IsValid)
{
db.entry(factory).State = EntityState.Modified;//<- Error here!
db.SaveChanges();
//Redirect
}
//Return view
}
When I try to get the Factory thats been changed I get the following error
A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
I'm trying to update the entire Factory object including the list of cars and TypeA & TypeB