使用 EF 查询相关 table 的最佳实践是什么
What is the best practice querying related table with EF
我有 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));
}
...
}
所以我的意思是我想return这样回应:
[
{
"id": "1",
"authorId": "asdasd-fg4543-fgfvc-45345-sdfsf",
"authorFullName": "Jane Doe",
"postContent": "Test Post by Jane Doe.."
}
]
Join
或以某种方式获取作者全名并放入同一条目的最佳做法是什么?
首先你必须将 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; }
}
表示没有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));
}
我有 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));
}
...
}
所以我的意思是我想return这样回应:
[
{
"id": "1",
"authorId": "asdasd-fg4543-fgfvc-45345-sdfsf",
"authorFullName": "Jane Doe",
"postContent": "Test Post by Jane Doe.."
}
]
Join
或以某种方式获取作者全名并放入同一条目的最佳做法是什么?
首先你必须将 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; }
}
表示没有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));
}