我使用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的出版物之后)
答案 0 :(得分:3)
如果您没有导航属性并且需要左外连接
,则可以使用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);
我还发现这个Query Expression Translation Cheat Sheet对于从查询表达式(更接近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);