我有Asp.Net Core 2
Web Api
申请,我使用Ef Core 2
Repository / Unit of Work
模式。我必须查询来自Database
的用户帖子,帖子实体如下所示:
public class Post
{
public int Id { get; set; }
// This is User Id from AspNetUsers
public string AuthorId { get; set; }
public string PostContent { get; set; }
}
在我的存储库中,我有查询:
public class FeedRepository : BaseRepository, IFeedRepository, IDisposable
{
public FeedRepository(ApplicationDbContext context) : base(context)
{
}
public IEnumerable<Post> GetPosts(string currentUserId, IEnumerable<string> followingUserIds)
{
// Which returns list of Post entities
return Db.Posts.Where(p => p.AuthorId == currentUserId || followingUserIds.Contains(p.AuthorId));
}
...
}
所以我的观点是我想要回复这样的回复:
[
{
"id": "1",
"authorId": "asdasd-fg4543-fgfvc-45345-sdfsf",
"authorFullName": "Jane Doe",
"postContent": "Test Post by Jane Doe.."
}
]
Join
或以某种方式获取作者全名并输入相同条目的最佳做法是什么?
答案 0 :(得分:1)
首先,您必须将Author
属性添加到Post
public class Post
{
public int Id { get; set; }
// This is User Id from AspNetUsers
public string AuthorId { get; set; }
public User Author { get; set; }
public string PostContent { get; set; }
}
表示在没有Post
的情况下无法创建User
。
使用Include
通过EF
public IEnumerable<Post> GetPosts(string currentUserId, IEnumerable<string> followingUserIds)
{
return Db.Posts.Include(it => it.Author).Where(p => p.AuthorId == currentUserId || followingUserIds.Contains(p.AuthorId));
}