如何使用特定值填充导航属性?
我有3个模型,Game,UserTeam,User,定义如下。我有一个使用IEnumerable模型的剃刀视图。此视图循环遍历游戏,并在该循环内循环用户团队。到目前为止,非常好。
在UserTeam循环中,我想访问User属性,但它们为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;
}
}
答案 0 :(得分:5)
您需要在存储库方法中包含它。如果您正在使用预先加载,那么它将类似于
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();
希望这可以帮助你