entity-framework - Entity Framework -如何使用导航属性添加到实体

标签 entity-framework

我想使用 Entity Framework 将记录添加到SQL Server表中。我表的实体具有外键,因此这些字段具有导航属性。添加新记录/实体时,由于外键字段未显示为实体的属性,我该如何填充?

最佳答案

最简单的方法是查询相关实体并使用导航属性:

IE。

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

如果要避免数据库查询,最简单的方法可能是使用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();

如果您需要有关此 stub 技术的更多帮助,请查看有关主题的blog post

关于entity-framework - Entity Framework -如何使用导航属性添加到实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1101077/

相关文章:

.net - 我可以使用数据注释通过 Entity Framework 4.1 RC 执行级联删除吗?

c# - dotnet ef 数据库更新无法加载文件或程序集“Microsoft.Extensions.FileProviders.Abstractions”

.net - Entity Framework 代码优先迁移错误

.net - 将 EF6 连接到 Oracle 11g DB 时不会显示数据源名称

entity-framework - 如何为 MS Access 数据库使用 Entity Framework

c# - 存储具有多个相同项目的集合

entity-framework - Entity Framework 3.5 和存储过程结果映射

c# - 使用EF4仅获得SQL表的最后一行的最有效方法是什么?

c# - 迁移 : No DbContext was found in assembly

c# - 如何使用 Entity Framework 从动态对象集 <t> 中动态获取对象 T 的属性?