【问题标题】:Entity Framework navigation property not set when adding entity添加实体时未设置实体框架导航属性
【发布时间】:2014-06-05 14:29:36
【问题描述】:

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

这就是我现在正在做的事情,导航属性 Condition 为空。我检查了外键是否已设置。我还尝试通过直接从另一个表中读取来手动分配 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.

【问题讨论】:

  • 你试过var group = _context.Groups.AddRange(groups).First().Include(x=>x.Condition);
  • 那行不通,甚至不能在那里使用 Include。在保存后更新我使用 Include 的实体。

标签: c# entity-framework navigation-properties


【解决方案1】:

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

您可以从类似的问题Navigation property returns null after inserting获取详细信息

【讨论】:

  • 该属性已被标记为虚拟。不过,我通过查看您的链接使其工作。 Include 做到了,但是我必须在保存后更新实体。
【解决方案2】:

这是我通过检查 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多