简体   繁体   English

实体框架中不可为空的导航属性为null

[英]Non nullable navigation property is null in Entity Framework

We have encountered Entity Framework returning NULL values for non-nullable relationships. 我们遇到了实体框架为非空关系返回NULL值的情况。 We work model first. 我们首先工作模型。 The problem occurs when an entity's relationship has been changed in a different context(or in our real use case: a different thread). 当实体的关系已在不同的上下文中更改(或在我们的实际用例中:不同的线程)时,就会发生问题。
-If the navigation property has NOT been called yet, it will return null. -如果尚未调用navigation属性,它将返回null。
-If the navigation property HAS been called before OR has a foreign key property included in the entity, it will return the last known value. -如果在实体中包含外键属性之前已调用了导航属性,则它将返回最后一个已知值。

  • Lazy loading is enabled for the model 为模型启用了延迟加载
  • I have tested this for Entity framework 4.0 and 6.0 and they both yield the same result 我已经针对Entity Framework 4.0和6.0进行了测试,它们都产生相同的结果

This is an example model: 这是一个示例模型:

在此处输入图片说明

This is some example test code that demonstrates the problem. 这是一些演示该问题的示例测试代码。

int ID;
using (Model1Container1 context = new Model1Container1())
{
    Dossier d = new Dossier();
    d.Fase = new Fase();
    context.DossierSet.AddObject(d);//generate new object with relationship
    context.SaveChanges();
    ID = d.Id;
}
using (Model1Container1 context = new Model1Container1())
{
    Dossier storedDossier = context.DossierSet.Single(x => x.Id == ID);//retrieve the saved entity
    using (Model1Container1 context2 = new Model1Container1())
    {
        Dossier faseDossier = context2.DossierSet.Single(x => x.Id == ID);//modify the saved entity in a different context
        faseDossier.Fase = new Fase();
        context2.SaveChanges();
    }
    Console.WriteLine(storedDossier.Fase.Id);//attempt to read the changed property. NULL exception here on storedDossier.Fase
}

This code does not use threads like in our real situation, but it describes the same problem. 该代码不像我们实际情况那样使用线程,但是它描述了相同的问题。 In the real application there can be a whole different application on a different PC modifying the entity in the database. 在实际的应用程序中,可以在不同的PC上使用一个完全不同的应用程序来修改数据库中的实体。

The question here is, why does this behavior occur? 这里的问题是,为什么会发生这种现象? Is this a bug in entity framework, perhaps? 这可能是实体框架中的错误吗?

It is clear to us that entity framework cannot retrieve the relationship that existed when the entity was instantiated because of lazy loading, but why won't it load the changed relationship instead? 我们很清楚,由于延迟加载,实体框架无法检索实例化实体时存在的关系,但是为什么不加载已更改的关系呢? Non nullable entities suddenly receiving NULL values is unexpected and something we have not considered in our code at all(and why should we in the first place?) 非可空实体突然接收到NULL值是意外的,我们在代码中根本没有考虑过这些(为什么我们首先要考虑?)

Replace 更换

context.DossierSet.Single(x => x.Id == ID);

with

context.DossierSet.Include(x => x.Fase).Single(x => x.Id == ID);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM