5

如何使用特定值填充导航属性?

我有 3 个模型,Game、UserTeam、User,定义如下。我有一个使用模型 IEnumerable 的剃刀视图。此视图循环遍历 Games,并在该循环内循环遍历 UserTeams。到现在为止还挺好。

在 UserTeam 循环中,我想访问 User 属性,但它们为空。如何为每个 UserTeam 对象填充用户导航属性?我需要在 UserTeam 模型中带有参数的构造函数吗?

楷模

public class Game
{
    public Game()
    {
        UserTeams = new HashSet<UserTeam>();
    }

    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<UserTeam> 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<UserTeam_Player> 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<UserTeam>();
    }

    public virtual ICollection<UserTeam> UserTeams { get; set; }
    [ForeignKey("CreatorId")]
    public virtual ICollection<Game> Games { get; set; }
}

在我的 Razor 视图中循环(模型是 IEnumerable)

@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 })
        }
}

我的存储库中返回游戏的方法

public IEnumerable<Game> GetAllGames()
    {
        using (DataContext)
        {
            var gm = DataContext.Games.Include("UserTeams").ToList();
            return gm;
        }
    }
4

1 回答 1

6

您需要将其包含在您的存储库方法中。如果您正在使用急切加载,那么它将类似于

var gm = DataContext.Games
                     .Include(x => x.UserTeams)
                     .Include(x => x.UserTeams.Select(y => y.User))
                     .ToList();

如果不使用 LINQ 进行查询,我没有这样做,但我认为它会是这样的:

var gm = DataContext.Games.Include("UserTeams.User").ToList();

希望这可以帮助你

于 2013-10-02T07:36:43.993 回答