繁体   English   中英

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

[英]Entity Framework adding existing Child to a new Parent on a many to many relation

当您想将现有的子级添加到新的父级(1对1或1-n关系)时,首先使用代码,您可以在父级内部定义Child以及ChileId和EF自动将ID映射到该子级。 有什么办法可以在多对多关系上做同样的事情?

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

体系结构数据:实体框架,代码优先。 后端webapi / restfull断开连接的UI将ParentData映射到ParentEntity Child集合就像是“国家”,因此我不想添加新的国家,而只是将许多国家与父级相关联。 用户界面上有一个多选下拉菜单,因此您可以选中/取消选中国家。

例如

父母与美国,英国有关

然后在用户界面上也有人检查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为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();
}

也许这可以帮助您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM