Fernando Torres
Fernando Torres

Reputation: 1180

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.

e.g.

Parent related with USA, UK

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

Upvotes: 0

Views: 2393

Answers (2)

grek40
grek40

Reputation: 13458

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

Upvotes: 2

muhammad hasnain
muhammad hasnain

Reputation: 501

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.

Upvotes: 0

Related Questions