Reputation: 3104
I have two classes, for instance:
class A {
public virtual ICollection<B> BList { get; set; }
}
class B {
public virtual ICollection<A> AList { get; set; }
}
Entity Framework then creates A and B tables and AB table that connects them.
In my application I get A_ID
and B_ID
, and I need to make connection between A and B.
What I did is fetch A by ID, then fetch B by ID, and then do A.BList.Add(BObject)
, but that is 3 database trips, 2 fetches + one insert.
Is there any way in Entity Framework to do it in one database trip?
UPDATE:
I looked at the link Martin provided, and wrote a simple example:
User user = new User { ID = 12135 };
Book book = new Book { ID = 1};
context.Users.Attach(user);
context.Books.Attach(book);
user.Books.Add(book);
context.SaveChanges();
But I got null pointer exception at user.Books.Add(book);
user.Books
is null, and it throws exception when Add is called...
Upvotes: 1
Views: 133
Reputation: 39326
You need to initialize your collection navigation properties in the entity's constructors:
public class A {
public A()
{
BList=new List<B>();
}
public virtual ICollection<B> BList { get; set; }
}
Do the same with the B
entity.
Also you don't need to attach the new entities at the beginning, to save them you can do this:
User user = new User { ID = 12135 };
Book book = new Book { ID = 1};
user.Books.Add(book);
context.Users.Add(user);
context.SaveChanges();
That's going to insert the three rows in just one database trip
Upvotes: 4
Reputation: 1296
Maybe you can resume your code and try this:
User user = new User {
ID = 12135 ,
Books = new ICollection<Book>() { new Book { ID = 1} }
};
context.Users.Attach(user);
Or:
User user = new User { ID = 12135 };
Book book = new Book { ID = 1};
context.Users.Attach(user);
context.Books.Attach(book);
user.Books = new ICollection<Book>();
user.Books.Add(book);
To resolve null pointer expection need to add a initializer to Books user collection, in code or in the User class constructor.
Upvotes: 1