EF sometimes returns null on foreign key types

mhcodner

I have a WebAPI controller that needs to return a collection from the database but I also need to remove some properties from some of the entities. However, for some reason the properties representing another entity returns null except for sometimes when I am stepping over the code in debug mode. I have shown the json response below which shows Sport, HomeTeam and AwayTeam as null:

enter image description here

But when I step over the code in debug mode I get the expected result:

enter image description here

The relevant controller method is as follows

public dynamic Get()
{
    var allPicks = _db.Picks;
    if (User.Identity.IsAuthenticated)
    {
        string userId = User.Identity.GetUserId();
        var picks = _db.UnlockedPicks
            .Include(p => p.SelectedPick.AwayTeam)
            .Include(p => p.SelectedPick.HomeTeam)
            .Include(p => p.SelectedPick.Sport)
            .Where(p => p.UserId == userId);

        var unlockedPicks = picks.Select(p => p.SelectedPick);
        var otherPicks = allPicks.Except(unlockedPicks).Select(p => new
        {
            Analysis = "",
            PickSummary = "",
            Title = p.Title,
            Id = p.Id,
            Sport = p.Sport,
            HomeTeam = p.HomeTeam,
            AwayTeam = p.AwayTeam,
            MatchTime = p.MatchTime,
            PublishTime = p.PublishTime
        });
        return new
        {
            UnlockedPicks = unlockedPicks.OrderByDescending(p => p.MatchTime),
            OtherPicks = otherPicks.OrderByDescending(p => p.MatchTime)
        };
    }
    var publicPicks = allPicks.OrderByDescending(p => p.MatchTime).Select(p => new
    {
        Analysis = "",
        PickSummary = "",
        Title = p.Title,
        Id = p.Id,
        Sport = p.Sport,
        HomeTeam = p.HomeTeam,
        AwayTeam = p.AwayTeam,
        MatchTime = p.MatchTime,
        PublishTime = p.PublishTime
    });
    return new { UnlockedPicks = new Pick[0], OtherPicks = publicPicks };
}

Without the Include() it returned null every time but how can I make it return the expected result every time?

Fabio Luz

It happens because you are not using lazy loading. When lazy loading is deactivated, you have to call Include in order to load the navigation properties. If you want load all navigation properties, without calling Include, will have to activate the lazy loading, which can be done through the context's constructor. Like this:

public partial class SchoolDBEntities : DbContext
{
    public SchoolDBEntities(): base("name=SchoolDBEntities")
    {
        this.Configuration.LazyLoadingEnabled = true;
    }
}

The lazy loading should be activated by default. You probably have deactivated it somewhere else in your code. It is also called automatically every time you inspect a navigation property in debug mode.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

FirstOrDefault returns null on foreign key

From Dev

SQL foreign key returns NULL

From Dev

EF Navigation Property with null foreign key

From Dev

DataContext always returns null as foreign key

From Dev

Dynamic cast unexpectedly returns null for a type, but only sometimes and not for other types

From Dev

MySQL foreign key ON DELETE SET NULL check data types error

From Dev

Foreign Key Types on Joins

From Dev

NSDateFormatter dateFromString sometimes returns null

From Dev

Why EF generate foreign key?

From Dev

Adding EF object as a foreign key

From Dev

EF cannot map a foreign key

From Dev

Foreign key is allowed to be NULL?

From Dev

yii null foreign key

From Dev

EF not allowing Foreign Key Column value Null though i Set it to Nullable

From Dev

MySQL Can Foreign Key Be Null

From Dev

foreign key always stays null

From Dev

Assigning UserId to Foreign Key = null

From Dev

mongodb belongsTo Foreign key is null

From Dev

Laravel Foreign Key can not be null

From Dev

foreign key always stays null

From Dev

Tastypie foreign key set null

From Dev

Update of the foreign key to a null value

From Dev

TweetSharp GetAccessToken method returns null but only sometimes

From Dev

Android camera intent returns null... sometimes

From Dev

why findviewbyposition( ) of recyclerView returns null only sometimes

From Dev

oracle ExecuteScalar in parallel programming sometimes returns null

From Dev

LINQ sub list<> sometimes returns "NULL"

From Dev

why findviewbyposition( ) of recyclerView returns null only sometimes

From Dev

Jersey response.readEntity(...) sometimes returns null