如何使用特定值填充导航属性?
我有 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;
}
}