Asp.net mvc 如何从多对多关系的导航属性中获取数据
这是邻里班,一个邻里可以有很多追随者:Asp.net mvc 如何从多对多关系的导航属性中获取数据,asp.net-mvc,entity-framework,linq-to-entities,many-to-many,anonymous-function,Asp.net Mvc,Entity Framework,Linq To Entities,Many To Many,Anonymous Function,这是邻里班,一个邻里可以有很多追随者: public class Neighbourhood { public Neighbourhood() { this.Followerss = new HashSet<ApplicationUser>(); } [Key] public int Id { get; set; } public string NeighbourhoodName { get; set; } //C
public class Neighbourhood
{
public Neighbourhood()
{
this.Followerss = new HashSet<ApplicationUser>();
}
[Key]
public int Id { get; set; }
public string NeighbourhoodName { get; set; }
//Calculated property
public virtual ICollection<ApplicationUser> Followerss { get; set; }
}
请建议我如何修改GetFollowers方法以返回正确的数据。首先,它的工作原理与预期一样,
SelectMany
从每个邻里区收集Applicationusers
,并将它们全部放在一个列表中,因此,当您投影它们时,您将获得ApplicationUser
的属性
其次,您试图做的是不可能的,您有一个多对多关系,因此根据定义,每个应用程序用户可以有多个邻域
,您如何期望每个应用程序找到一个邻域来获取id和名称等?我认为您正在寻找的关系是一对多的,每个邻居可以有多个applicationuser,但每个applicationuser只有一个邻居。当您将用户投影到邻域ProfileModel
中时,这将为您提供预期的行为
因此,您的ApplicationUser
模型如下所示:
public class ApplicationUser : IdentityUser<int, CustomUserLogin,CustomUserRole,>
{
public string Address { get; set; }
public virtual Neighbourhood NeighbourHood { get; set; }
}
公共类应用程序用户:IdentityUser
{
公共字符串地址{get;set;}
公共虚拟邻域{get;set;}
}
如果Applicationuser确实需要多个邻居,您也可以选择使用Select
,而不是SelectMany
。这将创建每个邻居的applicationuser列表。那么这个投影应该是可能的
您不需要中间表。您还需要将邻居
的主键与外键
属性一起作为属性添加到应用程序用户
。(除非您选择fluent mapping,这会更好)
(顺便说一句,由于您要投影到邻里档案模型中
,因此没有匿名函数,如果您有,则会出现这种情况。选择(u=>new{})
public virtual IEnumerable<NeighbourhoodProfileModel> GetFollowers(int userId)
{
var profiles = _context.Neighbourhoods
.SelectMany(u => u.Followerss)
.Select(u => new NeighbourhoodProfileModel
{
NeighbourhoodId = u.,
NeighbourhoodName = u.,
followersCount = u.,
IsFollowed = u.Followings.Any(user => user.Id == userId),
}).ToList();
return profiles;
}
public class NeighbourhoodProfileModel
{
public int NeighbourhoodId { get; set; }
public string NeighbourhoodName { get; set; }
public string City { get; set; }
public int postCount { get; set; }
public int followersCount { get; set; }
public int Followerss { get; set; }
public bool IsFollowed { get; set; }
}
public class ApplicationUser : IdentityUser<int, CustomUserLogin,CustomUserRole,>
{
public string Address { get; set; }
public virtual Neighbourhood NeighbourHood { get; set; }
}