C# 使用EF查询相关表的最佳实践是什么
我有C# 使用EF查询相关表的最佳实践是什么,c#,asp.net-core-2.0,asp.net-core-webapi,ef-core-2.0,C#,Asp.net Core 2.0,Asp.net Core Webapi,Ef Core 2.0,我有Asp.Net Core 2Web Api应用程序,我正在使用Ef Core 2和存储库/工作单元模式。我必须从数据库中查询用户帖子,帖子实体如下所示: public class Post { public int Id { get; set; } // This is User Id from AspNetUsers public string AuthorId { get; set; } public string PostContent { get;
Asp.Net Core 2
Web Api
应用程序,我正在使用Ef Core 2
和存储库/工作单元模式。我必须从数据库中查询用户帖子,帖子实体如下所示:
public class Post
{
public int Id { get; set; }
// This is User Id from AspNetUsers
public string AuthorId { get; set; }
public string PostContent { get; set; }
}
[
{
"id": "1",
"authorId": "asdasd-fg4543-fgfvc-45345-sdfsf",
"authorFullName": "Jane Doe",
"postContent": "Test Post by Jane Doe.."
}
]
在我的存储库中,我有一个查询:
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));
}
...
}
加入或以某种方式获取作者全名并放入同一条目的最佳做法是什么?首先,您必须将作者
属性添加到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; }
}
这表示没有User
就不能创建Post
使用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));
}
public IEnumerable GetPosts(字符串currentUserId,IEnumerable-UserId)
{
返回Db.Posts.Include(it=>it.Author).Where(p=>p.AuthorId==currentUserId | | followerUserId.Contains(p.AuthorId));
}