填充导航属性的导航属性 [英] Populating navigation properties of navigation properties
问题描述
如何使用特定值填充导航属性?
How do I populate a navigation property with specific value?
我有3个模型,分别是Game,UserTeam,User,定义如下.我有一个使用IEnumerable模型的剃刀视图.该视图在游戏"上循环,在该循环内,在"UserTeam"上循环.到目前为止,一切都很好.
I have 3 models, Game, UserTeam, User, defined below. I have a razor view which uses the model IEnumerable. This view loops over the Games, and within that loop, loops over the UserTeams. So far, so good.
在UserTeam循环中,我想访问User属性,但它们为null.如何为每个UserTeam对象填充用户导航"属性?我需要在UserTeam模型中使用带参数的构造函数吗?
Within the UserTeam loop, I want to access the User properties, but they are null. How do I populate the User navigation property for each UserTeam object? Do I need a constructor with a parameter in the UserTeam model?
模型
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)
Loop in my Razor view (Model is 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 })
}
}
我的存储库中返回游戏的方法
Method in my repository that returns the Games
public IEnumerable<Game> GetAllGames()
{
using (DataContext)
{
var gm = DataContext.Games.Include("UserTeams").ToList();
return gm;
}
}
推荐答案
您需要将其包含在存储库方法中.如果您使用的是紧急加载,则应该是
You would need to include this in your repository method. If you are using eager loading then it would be something like
var gm = DataContext.Games
.Include(x => x.UserTeams)
.Include(x => x.UserTeams.Select(y => y.User))
.ToList();
在没有使用LINQ进行查询的情况下,我并没有做到这一点,但是我认为它会是这样的:
I have not done this without using LINQ for my queries, but I assume it would be something like:
var gm = DataContext.Games.Include("UserTeams.User").ToList();
希望这对您有帮助
这篇关于填充导航属性的导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!