Note that there are some explanatory texts on larger screens.

plurals
  1. POPopulating navigation properties of navigation properties
    primarykey
    data
    text
    <p>How do I populate a navigation property with specific value?</p> <p>I have 3 models, Game, UserTeam, User, defined below. I have a razor view which uses the model IEnumerable. This view loops over the Games, and within that loop, loops over the UserTeams. So far, so good.</p> <p>Within the UserTeam loop, I want to access the User properties, but they are null. How do I populate the User navigation property for each UserTeam object? Do I need a constructor with a parameter in the UserTeam model?</p> <p>Models</p> <pre><code>public class Game { public Game() { UserTeams = new HashSet&lt;UserTeam&gt;(); } public int Id { get; set; } public int CreatorId { get; set; } public string Name { get; set; } public int CurrentOrderPosition { get; set; } public virtual UserProfile Creator { get; set; } public virtual ICollection&lt;UserTeam&gt; UserTeams { get; set; } } public class UserTeam { public UserTeam() { User = new UserProfile(); } public int Id { get; set; } public int UserId { get; set; } public int GameId { get; set; } public int OrderPosition { get; set; } public virtual UserProfile User { get; set; } public virtual Game Game { get; set; } public virtual IList&lt;UserTeam_Player&gt; UserTeam_Players { get; set; } } public class UserProfile { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } public string UserName { get; set; } public string test { get; set; } public UserProfile() { UserTeams = new HashSet&lt;UserTeam&gt;(); } public virtual ICollection&lt;UserTeam&gt; UserTeams { get; set; } [ForeignKey("CreatorId")] public virtual ICollection&lt;Game&gt; Games { get; set; } } </code></pre> <p>Loop in my Razor view (Model is IEnumerable)</p> <pre><code>@foreach (var item in Model) { @foreach (var userteam in item.UserTeams) { @Html.ActionLink("Join game as"+userteam.User.UserName, "JoinGame", new { gameid = item.Id, userid=userteam.UserId }) } } </code></pre> <p>Method in my repository that returns the Games</p> <pre><code>public IEnumerable&lt;Game&gt; GetAllGames() { using (DataContext) { var gm = DataContext.Games.Include("UserTeams").ToList(); return gm; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload