我想使用 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/