Entity Framework-How To Add To Entites With Navigational Properties

entity-framework

Question

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?

1
9
7/8/2009 11:25:04 PM

Accepted Answer

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.

15
5/30/2012 3:24:30 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow