Reputation: 1167
I want to get the below result in one query by linq methods such as .Where
, .Select
etc., is it possible?
Inner join is the better.
new {
Blog = MyDbContext.Blogs.SingleOrDefault(b => b.Url == "xxx.com"),
Post = MyDbContext.Posts.SingleOrDefault(p => p.Blog.Url == "xxx.com" &&
p.Author == "Jack")
}
Models:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Author { get; set; }
public Blog Blog { get; set; }
}
public class MyDbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
Upvotes: 0
Views: 76
Reputation: 26926
var ans = MyDbContext.Blogs.Where(b => b.Url == "xxx.com")
.Select(b => new {
Blog = b,
Post = b.Posts.Where(p => p.Author == "Jack").FirstOrDefault()
})
.SingleOrDefault();
Upvotes: 1