如何使用特定值填充导航属性?
我有3个模型,Game,UserTeam,User,定义如下.我有一个使用IEnumerable模型的剃刀视图.此视图循环遍历游戏,并在该循环内循环用户团队.到现在为止还挺好.
在UserTeam循环中,我想访问用户属性,但它们是null.如何为每个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; } }