简体   繁体   中英

Non nullable navigation property is null in Entity Framework

We have encountered Entity Framework returning NULL values for non-nullable relationships. 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.
-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

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.

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?)

Replace

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

with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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