实体框架将现有子级添加到多对多关系上的新父级



当您要将现有子级添加到新的父级(1 到 1 或 1-n 关系(时,首先使用代码,您只需在父级中定义子级,然后 ChileId 和 EF 将该 id 自动映射到子级。有没有办法对多对多关系做同样的事情??

Parent
{
int    ChildId {get;set;}
aClass Child {get;set;}
}

架构数据: 实体框架,代码优先。 后端webapi/restfull断开连接的UI将ParentData映射到ParentEntity 子集合类似于"countires",所以我不想添加新的,而只是将许多countires与Parent相关联。UI上有一个多选下拉菜单,因此您可以选中/取消选中国家/地区。

例如

父母与美国、英国有关

然后在UI上,有人还会检查ESP,3将与父级相关

在多对多中,使用 ID 而不是整个对象并不容易。

请考虑以下事项:

class Parent
{
public Parent()
{
Children = new List<Child>();
}
public int Id {get;set;}
public ICollection<Child> Children { get; set; }
}
class Child
{
public Child()
{
Parents = new List<Parent>();
}
public int Id {get;set;}
public ICollection<Parent> Parents { get; set; }
}

如果未加载现有子条目(并且不希望预加载(,则可以仅附加具有 ID 的子条目以建立关系:

int existingChildId; // some value
var childPlaceholder = new Child { Id = existingChildId };
db.Children.Attach(childPlaceholder);
var newParent = new Parent();
newParent.Children.Add(childPlaceholder);
db.Parents.Add(newParent);
db.SaveChanges();

如果您不知道子项是否已加载到上下文中,并且仍希望避免数据库查询来加载它,请检查local条目:

int existingChildId; // some value
var childPlaceholder = db.Children.Local.FirstOrDefault(x => x.Id == existingChildId) ??
db.Children.Attach(new Child { Id = existingChildId });
// placeholder is ready to use
using (var context = new YourContext())
{
var mathClass= new Class { Name = "Math" };
Student student1 = context.Students.FirstOrDefault(s => s.Name == "Alice");
Student student2 = context.Students.FirstOrDefault(s => s.Name == "Bob");
mathClass.Students.Add(student1);
mathClass.Students.Add(student2);
context.AddToClasses(mathClass);
context.SaveChanges();
}

也许这可以帮助你。

最新更新