user3885927
user3885927

Reputation: 3503

entity framework sets child object to null

I am having a rather strange issue with EF. I am displaying a list of scenarios that have an MfgSite associated with each of them. Below are the models:

//Models
public partial class Scenario
{

    public string Name { get; set; }
    public bool IsFinal { get; set; }
    public Guid Uid { get; set; }
    public string Username { get; set; }
    public string Description { get; set; }
    public Guid MfgSiteUid { get; set; }

//navigation property
    public MfgSite MfgSiteU { get; set; }

}


public partial class MfgSite
{
    public string MfgSiteCommonName { get; set; }
    public string MfgSiteState { get; set; }
    public string MfgSiteFunction { get; set; }
    public string MfgSiteDesc { get; set; }
    public Guid Uid { get; set; }

//navigation property
    public Scenario Scenario { get; set; }
}

In my Scenario controller Index Action I have this code below (Note that I generated models from db first using Scaffold-DbContext ). The returned list has MfgSiteU set to null on all except one entry for each unique MfgSiteUid in the scenario.

//Scenario Controller Index Action
public async Task<IActionResult> Index()
{
        var sContext = _context.Scenario.Include(s => s.MfgSiteU);
        return View(await sContext.ToListAsync());
}

When displayed in view (not all columns shown) it looks like this: enter image description here

The empty columns are because the s.MfgSiteU is null even though s.MfgSiteUid is accurate and not null. MfgSiteCommonName should have been "Test Site 1" for the second row and 'Test Site 2' for third and fourth rows.

What could cause this issue and what are the potential fixes? As part of my debugging, I tried to navigate one Scenario at a time using foreach on the DbSet and adding each one to List manually. I could see that MfgSiteU is not null on individual ones, but some how it resets the previous ones to null once I iterate towards the end.

Upvotes: 1

Views: 815

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205549

What could cause this issue and what are the potential fixes?

The problem is that according to the sample data, the relationship between Scenario and MfgSite is many-to-one, while the generated relationship is one-to-one. EF Core uses relationship cardinality when generating SQL joins needed to load the related data, which may lead to wrong results when the relationship is not mapped correctly.

The fix is to replace the navigation property in MfgSite from

public Scenario Scenario { get; set; }

to

public ICollection<Scenario> Scenarios { get; set; }

As of why the scaffold command created a wrong relationship, I can't answer without having the database model. In case you could provide a sample database reproducing the issue, I would suggest opening an issue in EFC issue tracker.

Upvotes: 2

Related Questions