[英]Get List ordered by number of records from another table using Linq
我正在使用EF6,我創建了這兩個模型:
public class Publication
{
public int Id { get; set; }
public string Name { get; set; }
public List<Product> Products { get; set; }
}
public class ViewLog
{
public int Id { get; set; }
public int? UserId { get; set; }
[ForeignKey("UserId")]
public User.User User { get; set; }
public int? SessionId { get; set; }
[ForeignKey("SessionId")]
public User.Session Session { get; set; }
public int PublicationId { get; set; }
[ForeignKey("PublicationId")]
public Publication.Publication Publication { get; set; }
public DateTime Created { get; set; }
}
每次訪問出版物時,我都會在ViewLog表中創建一條新記錄。 現在,使用Linq,我需要按照過去24小時內每個出版物的ViewLogs(訪問次數)排序所有出版物。 (如果Publication沒有ViewLogs,它們也需要出現,但顯然在具有viewlogs的出版物之后)
如果沒有導航屬性並且需要左外連接,則可以使用GroupJoin
lambda語法如下:
var publicationQuery = new List<Publication>().AsQueryable();
var viewLogQuery = new List<ViewLog>().AsQueryable();
var leftJoinQuery = publicationQuery
.GroupJoin(viewLogQuery, x => x.Id, x => x.PublicationId, (pub, logs) => new
{
PublicationId = pub.Id,
LogCount = logs.Count()
})
.OrderByDescending(x => x.LogCount);
我還發現這個查詢表達式翻譯備忘單對於從查詢表達式(更接近SQL)到lambda方法語法(我更喜歡)非常有用
如果你有一個導航屬性Publication.ViewLogs
(這是一個List<ViewLog>
),那么你可以使用帶有投影的Select()
var publicationQuery = new List<Publication>().AsQueryable(); // From a DbSet...
var query = publicationQuery
.Select(x => new
{
PublicationId = x.Id,
LogCount = x.ViewLogs.Count
})
.OrderByDescending(x => x.LogCount);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.