views:

1157

answers:

1

I would like to add a record to a SQL Server table using the Entity Framework. My table's entity has foreign keys and so has navigational properties for those fields. When adding a new record/entity, how do I populate the foreign key fields since they don't appear as properties of the entity?

+2  A: 

The easiest way is to do a query for the related entities and use the Navigation Properties:

i.e.

Product p = new Product{
   ID = 5,
   Name = "Bovril",
   Category = ctx.Categories.First( c => c.ID == 5)
};
ctx.AddToProducts(p);
ctx.SaveChanges();

If you want to avoid the database query the easiest approach is probably to use a STUB entity i.e.

// this is a stub, a placeholder for the real entity
Category c = new Category {ID = 5}; 
// attach the stub to the context, similar to do a query
// but without talking to the DB
ctx.AttachTo("Categories", c);
Product p = new Product{
   ID = 5,
   Name = "Bovril",
   Category = c
};
ctx.AddToProducts(p);
ctx.SaveChanges();

If you want more help on this stub technique check out this blog post on the topic.

Hope this helps

Alex

Alex James
I tried the suggested answers and they both worked great. Thanks so much for your help!