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

本文关键字:实体 导航 属性 框架 添加 设置 | 更新日期: 2023-09-27 18:07:07

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

这是我现在在做的,导航属性条件是空的。我检查了外键是否已设置。我还尝试通过直接从其他表读取手动分配给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.

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

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

来使用即时加载导航属性在插入
后返回null

通过检查Ankit Sinha提供的链接,我是如何让它工作的:

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