添加实体时未设置实体框架导航属性

时间:2014-06-05 14:29:36

标签: c# entity-framework navigation-properties

当我向表中添加新实体时,我希望在保存更改后填充导航属性。我该怎么做?

这是我现在正在做的事情,导航属性Condition为null。我已检查外键是否已设置。我还尝试通过直接从另一个表中读取来手动分配到nav属性,但即使这样也不起作用。

...
var group = _context.Groups.AddRange(groups).First();
await _context.SaveChangesAsync();
// group.Condition which is a navigation property is null after this. 
// The property does work when I get the group from the context, after adding.

2 个答案:

答案 0 :(得分:4)

禁用延迟加载时会出现这种情况。通过向属性添加virtual关键字来启用它。您还可以使用_context.Groups.Include("Condition")

来使用预先加载

您可以从类似问题Navigation property returns null after inserting

中获取详细信息

答案 1 :(得分:0)

通过查看Ankit Sinha提供的the link来了解我的工作方式:

var group = _context.Groups.AddRange(groups).First();
await _context.SaveChangesAsync();
var group = _context.Groups.Include(x => x.Condition).SingleOrDefaultAsync(x => x.Id == group.id);
相关问题