我想使用Entity Framework将记录添加到SQL Server表中.我的表的实体具有外键,因此具有这些字段的导航属性.添加新记录/实体时,如何填充外键字段,因为它们不显示为实体的属性?
Ale*_*mes 15
最简单的方法是对相关实体进行查询并使用导航属性:
即
Product p = new Product{
ID = 5,
Name = "Bovril",
Category = ctx.Categories.First( c => c.ID == 5)
};
ctx.AddToProducts(p);
ctx.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
如果要避免数据库查询,最简单的方法可能是使用STUB实体即
// 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();
Run Code Online (Sandbox Code Playgroud)
如果您需要有关此存根技术的更多帮助,请查看此主题的博客文章.
| 归档时间: |
|
| 查看次数: |
6920 次 |
| 最近记录: |