这听起来很奇怪,但实际上很简单。
我有以下课程:
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中删除
有谁知道我做错了什么?
祝你好运
答案 0 :(得分:0)
您的Cat
- Platillo
关系为* -1或多对一。 Cat
只能有一个Platillo
而Platillo
可以有多个Cat
。
Cat
表中有一个外键,如果你将它分配给Platillo2,它会被重写。
考虑在Cat
和Platillo
之间使用多对多关系。您的数据库中将有另外的表存储Cat
和Platillo
个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