【问题标题】:How to join 2 tables using linq but avoid anonymous object如何使用 linq 加入 2 个表但避免匿名对象
【发布时间】:2016-05-06 18:27:25
【问题描述】:

我想使用 linq 加入 2 个表并避免使用匿名对象。

到目前为止,我使用元组。

var products = from tm in db.TargetMarkets
                join tp in db.Products on tm.product_id equals tp.id
                where tm.country == 2
                select Tuple.Create<TargetMarket, Product>(tm, tp);

但是,当我 foreach

foreach (var p in products)
{
    var a = p.Item1.id;
}

抛出异常

LINQ to Entities 无法识别方法 'System.Tuple`2

问题

  1. 有没有办法让我的代码保持强类型化
  2. 元组有什么问题(可选)

【问题讨论】:

  • 我怀疑错误是因为使用了连接条件的类型,你能检查两个 Id 的类型相同吗?
  • 您注意到foreach 中的错误,因为第一个语句是延迟执行。
  • 它们是相同的类型(整数)。查询语句不抛出错误。 foreach 执行抛出错误。

标签: c# entity-framework linq linq-to-entities strong-typing


【解决方案1】:

有没有办法让我的代码保持强类型

您可以定义一个新类型并创建该类型的对象而不是匿名对象。

class ProductTargetMarket
{
   //Attributes
} 

var ProductsTargetMarkets = from tm in db.TargetMarkets
            join tp in db.Products on tm.product_id equals tp.id
            where tm.country == 2
            select new ProductTargetMarket{Attribute1OfProductTargetMarket = tp.Attribute1, Attribute1OfProductTargetMarket = tm.Attribute1 };

要创建元组,您可以先将其转换为匿名类型,然后再将其转换为元组,请参阅此thisthis 帖子。

【讨论】:

  • 谢谢。有用!。我只是想知道“linq 查询”的语法,首先返回匿名类型并将其转换为元组。 (可选和谷歌搜索):)
猜你喜欢
  • 1970-01-01
  • 2019-09-09
  • 1970-01-01
  • 2018-09-04
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 2012-11-17
相关资源
最近更新 更多