【问题标题】:Populating navigation properties of navigation properties填充导航属性的导航属性
【发布时间】:2013-10-02 22:10:37
【问题描述】:

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

我有 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;
        }
    }

【问题讨论】:

  • Thewads 答案与@Slaumas 评论相结合解决了这个问题。问题仍然存在,为什么在 Game 构造函数中实例化 UserTeams 不会导致与在 UserTeam 构造函数中实例化用户相同的问题

标签: asp.net-mvc entity-framework


【解决方案1】:

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

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();

希望对你有所帮助

【讨论】:

  • @jag:Thewads 的回答是正确的。但是您还有另一个问题:您必须从UserTeam 构造函数中删除User = new UserProfile();。这会导致加载的用户不会被分配给User 属性并导致未初始化的用户。我相信当您删除该行时它会起作用。
  • @Slauma - 问题虽然 - 我在游戏构造函数 (UserTeams = new HashSet();) 中有相同的行,但效果很好(UserTeams 填充正确)???
  • @jag: 在构造函数中初始化 empty 导航 collections 不是问题,只有单个对象引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多