簡體   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