c# - 使用Entity Framework查询多表联合结果

标签 c# entity-framework

我想查询 3 个表并获取所有表的最新事件,由 CreatedDate 时间戳确定。每个表都由我的域模型中的一个实体表示,我正在使用 Entity Framework Code First(无数据迁移)来映射我的域。

我知道查询在 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

最佳答案

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

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 }));

关于c# - 使用Entity Framework查询多表联合结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14319763/

相关文章:

c# - 如何在 EF 中更新父实体时添加/更新子实体

.net - Entity Framework 中使用代码优先的 TVF(表值函数)

c# - 如何判断数据库记录是否已更改?

c# - 如何在 C# 中不区分大小写地解析 float 和 double (以覆盖 "infinity"等)?

c# - 撤消 checkout TFS

c# - 处理多相机捕获 UWP

c# - Entity Framework 6 和集合

javascript - jQuery 弹出窗口不显示内部带有方括号的字符串

c# - 如何从服务器加载 Dicom 图像(路径包含 https ://)

mysql - MSTest 预期异常测试失败