简体   繁体   中英

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

When you want to add an existing Child to a new Parent (1 to 1 or 1-n relation), working with code first, you can just define inside Parent the Child and ChileId and EF automap that id to the child. Is there any way to do the same on a many to many relation??

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

architecture data: Entity Framework, code first. Backend webapi/restfull disconnected UI maps a ParentData to ParentEntity Child collection would be something like "countires", so I dont want to add new ones, but just relate many countires to the Parent. There is a multiselect drop-down on the UI, so you can check/uncheck the countries.

eg

Parent related with USA, UK

Then at UI someone also checks ESP the 3 will be related to the Parent

In many-to-many, it's not as easy to work with ID instead of whole objects.

Consider the following:

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; }
}

If the existing child is not loaded (and not wanted to be pre-loaded), you can attach a child entry with ID only to establish the relation:

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();

If you don't know whether the child is already loaded in the context and you still want to avoid a database query to load it, inspect the local entries:

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();
}

may be this could help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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