将外部对象添加到Entity Framework 6.1中的另一个外部对象后删除

时间:2016-04-21 16:36:35

标签: entity-framework

这听起来很奇怪,但实际上很简单。

我有以下课程:

public class Platillo
{
    [Key] 
    public int ID { get; set; }
    // ..Several properties
    public virtual ICollection<Cat> Cats { get; set; }
}

public class Cat
{
    [Key] 
    public int ID { get; set; }
    public string Name { get; set; }
}

然后当我更新Platillo对象时,我会执行以下操作:

public JsonResult Edit(Platillo p)
{
    Platillo pAux = Bd.Platillos.Include("Cats")
                      .Single<Platillo>(x => x.ID == p.ID);

    pAux.Name = p.Name;
    // Setting several properties
    pAux.Categorias.Clear();

    foreach (Cat c in p.Cats)
    {
        Categoria cc = Bd.Cats.Single<Cat>(ca => ca.ID == c.ID);
        pAux.Cats.Add(cc);
    }

    Bd.SaveChanges();

    return Json(pAux.ID);
} 

让我们说数据库中有这些对象:

Cat_1

Platillo1
Platillo2

问题在于,如果将对象Cat1分配给Platillo1然后将其分配给Platillo2,它将从Platillo1中删除

有谁知道我做错了什么?

祝你好运

1 个答案:

答案 0 :(得分:0)

您的Cat - Platillo关系为* -1或多对一。 Cat只能有一个PlatilloPlatillo可以有多个Cat

Cat表中有一个外键,如果你将它分配给Platillo2,它会被重写。

考虑在CatPlatillo之间使用多对多关系。您的数据库中将有另外的表存储CatPlatillo个ID。您将没有此表的相应模型类。 EF将隐式使用它。

查看this link以了解在EF中配置多对多关系。

如果您使用的是代码优先方法,请尝试将模型类更改为此

public class Cat
{
    [Key] 
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Platillo> Platillos { get; set; }
}
  

还有其他方法吗?我宁愿不添加属性。

是的,有一种方法可以使用流畅的API。将此代码放入上下文类的OnModelCreating方法。

modelBuilder.Entity<Platillo>()
    .HasMany(p => p.Cats)
    .WithMany() // <- no parameter here because there is no navigation property