[英]How to convert SQL Left Join query to Linq to Entity in C#?
[英]how to convert left outer join sql query into entity framework 5.0?
using (database db = new database())
{
var query = (
from c in db.tblBlogs
join a in db.tblBlogMedias on c.id equals a.BlogId
select new
{
c.id,
c.CreatedDate,
c.Author,
c.BlogTitle,
c.BlogDescription,
a.BlogId,
a.BlogPicturePath
}).OrderByDescending(d => d.id).ToList();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
query.ToList().ForEach(x =>
{
sb.Append(string.Format("<div class='col-sm-4
wow fadeInUp animated' data-wow-duration='1000ms' data-wow-delay='400ms'
style='visibility: visible; animation-duration: 1000ms; animation-delay:
400ms; animation-name: fadeInUp;'><div class='post-thumb'><div class='post-
meta'>"+
"</div>"+
"</div>"+
"<div class='entry-
header'><h3><a href='#'>{0}</a></h3><span class='date'>{1}</span></div>
</div>",x.BlogTitle,x.CreatedDate));
});
}
如何在 var query = 中編寫此 sql 查詢:
select tblBlog.*,tblBlogMedia.BlogPicturePath from tblBlog left outer join
tblBlogMedia on tblBlog.id = tblBlogMedia.BlogId
where tblBlogMedia.id=(select max(id) from tblBlogMedia where BlogId='2')
使用正確命名的實體和導航屬性,它看起來像這樣:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EfDbFirstTest
{
public class Blog
{
public int Id { get; set; }
public DateTime CreatedDate { get; set; }
public string Author { get; set; }
public string BlogTitle { get; set; }
public string BlogDescription { get; set; }
public ICollection<BlogMedia> BlogMedia { get; set; }
}
public class BlogMedia
{
public int Id { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
public string BlogPicturePath { get; set; }
}
public class Db : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<BlogMedia> BlogMedia { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (var db = new Db())
{
db.Database.Log = m => Console.WriteLine(m);
var q = from b in db.Blogs
select new
{
b.Id,
b.CreatedDate,
b.Author,
b.BlogTitle,
b.BlogDescription,
BlogPicturePath = b.BlogMedia.Any() ? b.BlogMedia.OrderByDescending(m => m.Id).FirstOrDefault().BlogPicturePath : null
};
var results = q.ToList();
Console.ReadKey();
}
}
}
}
這就是我想要的完美工作方式,我在 ForEach 循環體中編寫此代碼,然后在 sb.append 中傳遞 q 的值:
var q = (from d in db.tblBlogMedias
join c in db.tblBlogs on d.BlogId equals x.id
select new
{
d.Id,
d.BlogPicturePath
}).OrderByDescending(d=>d.Id).Max(d => d.BlogPicturePath);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.