How to handle Foreign Keys with Entity Framework
I have two entities. Groups. Pools. A Group can create many pools.
So I setup my Pool table to have a GroupID foreign key.
My code:
using (entity _db = new entity()) {
Pool p = new Pool();
p.Name = "test";
p.Group.ID = "5";
_db.AddToPool(p);
}
This doesn't work. I get a null reference exception on p.Gr开发者_开发技巧oup.
How do I go about creating a new "Pool" and associating a GroupID?
You can either load the existing Group object, say group
, from your context and then set p.Group = group
or with EF4 you can set the GroupID
on your pool directly since it can expose the foreign key properties if you specify that in the EDMX.
精彩评论