【发布时间】:2018-01-08 12:35:46
【问题描述】:
考虑以下类:
public class Unidade
{
public int UnidadeId { get; set; }
public string Apelido { get; set; }
public string Descricao { get; set; }
}
和
public class Estrutura
{
public int Id { get; set; }
…
public int UnidadeId { get; set; }
public virtual Unidade Unidade { get; set; }
…
public int UnidadeCompraId { get; set; }
public virtual Unidade UnidadeCompra { get; set; }
…
}
查询 Estruturas.Single(e => e.Id == 120898).Unidade.Descricao 会返回错误,实际上是因为 Estruturas.Single(e => e.Id == 120898).Unidade 为空。
此示例中使用的 Id (120898) 有效,因为设置了有效的 UnidadeId 值。
怎么了?如何获得具有有效 Estrura 的 Descricao 的价值?
【问题讨论】:
-
您可以尝试预先加载 (
Estruturas.Include(e => e.Unidade.Single(e => e.Id == 120898).Unidade.Descricao) 尽管您的导航属性设置为延迟加载并且代码应该按原样工作(除非存在模型配置问题或延迟加载/代理创建是为上下文禁用)。有流畅的配置吗? -
实际上这个问题第一次出现在 MVC 急切加载中,我简化了它,在这里隔离了 EF 模式......它不会工作
-
如果你有 null 值然后将 int 更改为 int?
-
我没有空值,这就是问题所在......
标签: c# .net sql-server database entity-framework