【问题标题】:making Union for three different entities that implements the same interface为实现相同接口的三个不同实体创建联合
【发布时间】:2011-06-05 12:07:29
【问题描述】:

我有 3 个实体:RatedPrice、DailyPrice 和 UtilizePrice。
每个实体都有代码成员。

我想编写一个 lambda 查询,返回按 Code 成员排序的三个 IQueryable。我知道我需要在 Union 的某个地方使用,但我不知道如何使用。 此外,所有 3 个实体都有差异,但都实现了 IPrice。

如何查询?

【问题讨论】:

标签: c# .net entity-framework lambda linq-to-entities


【解决方案1】:

你必须使用这样的东西:

var data = ctx.RatedPrices.Select(p => new { p.Code, p.Price })
              .Concat(ctx.DailyPrices.Select(p => new { p.Code, p.Price })
                         .Contact(ctx.UtilizePrices.Select(p => new { p.Code, p.Price }))
              .OrderBy(p => p.Code);

实体框架和 linq-to-entities 不知道接口是什么。您必须对某些未映射的类型(示例中为匿名)使用投影并处理结果。因为您不使用来自某些基础 Price 的实体继承(否则您将不需要它),您不能期望 EF 会在单个结果集中返回您的 RetedPriceDailyPriceUtilizePrice 实例。

【讨论】:

    【解决方案2】:

    可能是这样的

    var list = listRatedPrice.Cast<IPrice>()
    .Concat(listDailyPrice.Cast<IPrice>()
    .Concat(listUtilizePrice.Cast<IPrice>))).Orderby(p => p.Code);
    

    【讨论】:

    • 它返回 IQueryable 吗?我不能让 concat 出现在 .Net 上,因为每种类型都有很多元素。
    • 好吧,我不这么认为,SQL中没有接口的概念。您必须从每个表中选择所需的列(例如名称、价格、代码...),然后将它们连接起来。
    • 此外,如果您要在排序后将所有项目都编码,那么您是在代码中还是在 SQL Server 中进行排序都没有关系。
    • 这是一个异常,因为 IPrice 不是实体。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    相关资源
    最近更新 更多