使用entityframework保存相关模型 - 发生了参照完整性约束违规

时间:2014-11-21 10:19:43

标签: c# entity-framework

我有以下型号

工厂可以有多辆汽车,一辆汽车可以有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;}
}

使用以下

在EditorTemplate中显示
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();

我只是发布模型进行查看,依此类推。然后是时候将数据发布回模型了。

我有以下操作,这是我的帖子。

public ActionResult FactoryEdit(Factory factory)
{
    if(ModelState.IsValid)
    {
        db.entry(factory).State = EntityState.Modified;//<- Error here!
        db.SaveChanges(); 
        //Redirect
    }
    //Return view
}

当我尝试更改Factory时,我收到以下错误

发生了引用完整性约束违规:定义引用约束的属性值在关系中的主体和从属对象之间不一致。

我试图更新整个Factory对象,包括汽车列表和TypeA&amp; TypeB

0 个答案:

没有答案