C# 如何使用linq连接2个表,但避免匿名对象
我想使用linq连接两个表并避免匿名对象 到目前为止,我使用tupleC# 如何使用linq连接2个表,但避免匿名对象,c#,entity-framework,linq,linq-to-entities,strong-typing,C#,Entity Framework,Linq,Linq To Entities,Strong Typing,我想使用linq连接两个表并避免匿名对象 到目前为止,我使用tuple 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>
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);
它抛出一个异常
LINQ to实体无法识别方法“System.Tuple”2
问题:
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 };
要创建一个元组,您可以先将其转换为匿名类型,然后再将其转换为元组,请参见本文并发布 我怀疑错误是因为使用了连接条件的类型,您能检查两个ID是否属于同一类型吗?您在
foreach
中注意到错误,因为第一个语句是deferred execution。它们是相同的类型(integer)。查询语句未引发错误。foreach执行抛出错误。谢谢。它起作用了!。我只是想知道“linq查询”的语法,首先返回匿名类型并将其转换为元组。(可选和谷歌搜索):)
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 };