Entity Framework 6 not loading Navigation Properties (lazy Loading)

.net asp.net asp.net-mvc c# entity-framework-6

Question

im trying to load the following Database structur

User -> UserTeamRelation -> Team -> Game

In this relation "Team" is already null when trying to access "user.Teams.Team".

I have the following Database structure

public class User : IdentityUser
{
    public User()
    {
        this.Id = Guid.NewGuid().ToString();
    }

    public virtual ICollection<TeamMember> Teams { get; set; }
}

public class Team
{
    public Team()
    {
        this.Id = Guid.NewGuid().ToString();
    }

    [Key]
    public string Id { get; set; }

    public virtual ICollection<TeamMember> Memberinos { get; set; }

    [Required]
    public virtual Game Game { get; set; }
}

public class TeamMember
{
    public TeamMember()
    {
        this.Id = Guid.NewGuid().ToString();
    }

    [Key]
    public string Id { get; set; }

    public virtual Team Team { get; set; }

    public virtual User Member { get; set; }
}

public class Game
{
    public Game()
    {
        this.Id = Guid.NewGuid().ToString();
    }

    [Key]
    public string Id { get; set; }

    public string Name { get; set; }
}

I tried the following code

using (var db = new ApplicationDbContext())
{
    var user = db.Users.FirstOrDefault(x => x.UserName.ToLower().Equals(username));
    if (user == null)
    {
        return new ResponseViewModel(false, "User nicht gefunden", null);
    }

    var teams = new List<Team>();
    foreach (var team in user.Teams)
    {
        teams.Add(new Team()
        {
            Description = team.Description,
            TeamName = team.Team.TeamName,
            GameName = team.Team.Game.Name
        });
    }
}

it reaches the foreach loop and finds the "Description" property. but when i try to access the team model, its null.

Any suggestion?

1
0
3/18/2017 3:07:11 AM

Accepted Answer

okay. after some research i found out, that just the team entity didn't exist because of inconsistent data / a broken database.

Thank you for your help.

The solution with ".Include("Teams.Team.Game")" did the trick as well

0
3/18/2017 2:59:31 PM

Popular Answer

There should be a foreign key in the TeamMember model class:

public class TeamMember
{
    public TeamMember()
    {
        this.Id = Guid.NewGuid().ToString();
    }

    [Key]
    public string Id { get; set; }

    [Required]
    public string TeamId { get; set; }

    [ForeignKey("TeamId")]
    public virtual Team Team { get; set; }

    [Required]
    public string UserId { get; set; }

    [ForeignKey("UserId")]
    public virtual User Member { get; set; }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow