如何使用 linq 连接 2 个表但避免匿名对象
How to join 2 tables using linq but avoid anonymous object
我想使用 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 does not recognize the method 'System.Tuple`2
问题:
- 有没有办法让我的代码保持强类型化
- 元组有什么问题(可选)
Is there a way to keep my code strong type
您可以定义一个新类型并创建该类型的对象而不是匿名对象。
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 };
要创建元组,您可以先将其转换为匿名类型,然后再将其转换为元组,请参阅此 this and this post。
我想使用 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 does not recognize the method 'System.Tuple`2
问题:
- 有没有办法让我的代码保持强类型化
- 元组有什么问题(可选)
Is there a way to keep my code strong type
您可以定义一个新类型并创建该类型的对象而不是匿名对象。
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 };
要创建元组,您可以先将其转换为匿名类型,然后再将其转换为元组,请参阅此 this and this post。