我想查询 3 个表并获取所有表的最新活动,由 CreatedDate 时间戳确定。每个表都由我的域模型中的一个实体表示,并且我使用实体框架代码优先(无数据迁移)来映射我的域。
我知道查询在 SQL 中应该是什么样子,但我不确定如何在 LinqToEntities 或 EntitySql 中制作它。您能否告诉我如何在 Entity Framework 中执行此操作,即使使用 Entity Framework 查询方法执行此查询是否合适?
在此先感谢您的帮助。
这是我的实体(主键在基类上):
public class Group : EntityThatBelongsToApartmentComplex<int>
{
public string GroupName { get; set; }
public string GroupDescription { get; set; }
[Required]
public DateTimeOffset CreatedDate { get; protected set; }
public int CreatedById { get; set; }
public virtual UserProfile CreatedBy { get; set; }
}
public class Activity : EntityThatBelongsToApartmentComplex<int>
{
[StringLength(150)]
public string Name { get; set; }
[StringLength(150)]
public string Description { get; set; }
public int CreatedById { get; set; }
public virtual UserProfile CreatedBy { get; set; }
[Required]
public DateTimeOffset CreatedDate { get; protected set; }
}
public class Comment : EntityBase<int>
{
[StringLength(200)]
public string Text { get; set; }
public int CreatedById { get; set; }
public virtual UserProfile CreatedBy { get; set; }
[Required]
public DateTimeOffset CreatedDate { get; protected set; }
}
这是我对 SQL 中查询应该是什么样子的感觉:
WITH NewsFeed AS (
SELECT
g.Id AS ItemId
,'Group' AS ItemType
,g.GroupName AS HeaderText
,g.CreatedDate
,g.CreatedById AS CreatorId
,u.UserName AS CreatorName
FROM Groups g
INNER JOIN UserProfiles u on g.CreatedById = u.Id
UNION
SELECT
a.Id AS ItemId
,'Activity' AS ItemType
,a.Name AS HeaderText
,a.CreatedDate
,a.CreatedById AS CreatorId
,u.UserName
FROM Activities a
INNER JOIN UserProfiles u on a.CreatedById = u.Id
UNION
SELECT
c.Id AS ItemId
,'Comment' AS ItemType
,c.Text AS HeaderText
,c.CreatedDate
,c.CreatedById AS CreatorId
,u.UserName
FROM Comments c
INNER JOIN UserProfiles u on c.CreatedById = u.Id
)
SELECT TOP 10 *
FROM NewsFeed
ORDER BY CreatedDate