实体框架-如何添加到具有导航属性的实体 [英] Entity Framework-How To Add To Entites With Navigational Properties
问题描述
我想使用实体框架将记录添加到SQL Server表中。我表格的实体具有外键,因此这些字段具有导航属性。添加新记录/实体时,如何填充外键字段,因为它们不会显示为实体的属性?
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?
推荐答案
最简单的方法是查询相关实体并使用导航属性:
The easiest way is to do a query for the related entities and use the Navigation Properties:
ie
Product p = new Product{
ID = 5,
Name = "Bovril",
Category = ctx.Categories.First( c => c.ID == 5)
};
ctx.AddToProducts(p);
ctx.SaveChanges();
如果要避免数据库查询,最简单的方法可能是使用STUB实体,即
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.
这篇关于实体框架-如何添加到具有导航属性的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!