gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:21:29 32 4
gpt4 key购买 nike

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

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com