查询EF相关表的最佳实践是什么?

时间:2018-04-01 09:55:12

标签: c# asp.net-core-2.0 asp.net-core-webapi ef-core-2.0

我有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或以某种方式获取作者全名并输入相同条目的最佳做法是什么?

1 个答案:

答案 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));
}