【问题标题】:Selecting Posts of Users whom I am following选择我关注的用户的帖子
【发布时间】:2017-07-21 15:52:08
【问题描述】:

我有两个模型:

public class UserProfile {
     public int Id { get; set; }
     public virtual ICollection<UserProfile> Following { get; set; }
     public virtual ICollection<Post> Posts { get; set; }
}

public class Post {
     public int Id { get; set; }
     public virtual UserProfile { get; set; }
}

我想选择当前用户关注的用户的所有帖子。这基本上就像显示您在社交网站上关注的人的帖子的提要。我如何在 linq 中执行此操作?我收到了一个错误。

var following = CurrentUser.UserProfile.Following;
var posts = (from p in db.Posts
                      where following.Any(a=>a.Id == p.UserProfile.Id)
                      select new Post).ToList();

【问题讨论】:

  • 错误是什么?
  • 以上代码优先代码缺少某些内容。你能展示一下实际的数据库图吗?

标签: asp.net asp.net-mvc linq


【解决方案1】:

您可以使用导航属性来获取结果:

var result=CurrentUser.UserProfile.Following.SelectMany(u=>u.Posts);

我认为问题出在您身上,因为您正试图将查询投影到实体类 (Post)。在 EF 中,您只能将查询投射到匿名类型或 DTO(自定义类)。

按照您的想法执行此操作的另一种方法是:

var following = CurrentUser.UserProfile.Following.Select(u=>u.Id);
var posts = (from p in db.Posts
                      where following.Contains(p.UserProfile.Id)
                      select p).ToList();

Contains 扩展方法在 SQL 中被转换为 IN

【讨论】:

    猜你喜欢
    • 2020-04-18
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    相关资源
    最近更新 更多