【发布时间】:2016-01-20 06:57:01
【问题描述】:
这是 Neighborhood 类,一个社区可以有很多关注者:
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; }
}
这是我的 ApplicationUser 类,一个用户可以关注多个邻居:
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,>
{
public string Address { get; set; }
public ApplicationUser()
{
this.Followings = new HashSet<Neighbourhood>();
}
public virtual ICollection<Neighbourhood> Followings { get; set; }
现在,这两者之间存在多对多关系,因此,它在数据库中创建了一个名为 NeighbourhoodApplicationUsers 的新表,其中包含列(Neighbourhood_Id 和 ApplicationUser_Id)。
现在,我想要一个方法可以返回 Neighborhood 的追随者所以,我写了这个:
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;
}
我不知道如何在这里建模这个匿名函数,我被困在这里,我想可能是我做错了。将 (.)dot 放在 u 之后,它应该返回 u.NeighbourhoodName 类似的东西,但它返回与用户相关的数据,而不是获取与邻域类相关的数据。
如果我注释掉 .SelectMany(u => u.followerss) 行,那么我会在匿名函数中获得所有必需的属性。
这是我的视图模型:
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; }
}
请建议我如何修改 GetFollowers 方法以返回正确的数据。
【问题讨论】:
标签: asp.net-mvc entity-framework linq-to-entities many-to-many anonymous-function