Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用linq连接2个表,但避免匿名对象_C#_Entity Framework_Linq_Linq To Entities_Strong Typing - Fatal编程技术网

C# 如何使用linq连接2个表,但避免匿名对象

C# 如何使用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>

我想使用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>(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 };