使用实体框架查询多个表的联合结果

时间:2013-01-14 13:54:31

标签: c# entity-framework

我想查询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

1 个答案:

答案 0 :(得分:3)

您需要使用投影。只需将每个查询的结果投影到具有相同参数的匿名(或非匿名)对象(名称和类型必须匹配)。然后你可以做这样的事情:

var query =
    context.SetOne.Select(x => new { Key = x.ID })
        .Union(context.SetTwo.Select(x => new { Key = x.AnotherKey }))
        .Union(context.SetThree.Select(x => new { Key = 5 }));