简体   繁体   English

LINQ在具有不同数据类型的多列上联接

[英]LINQ Join On Multiple Columns With Different Data Types

I've got a situation where I need to join two tables based on two columns, and one of the columns that is to be compared is a nullable integer while one is a string (a big mess I know). 我有一种情况,我需要基于两个列连接两个表,要比较的列之一是可为空的整数,而一个是字符串(我知道这很糟)。 In SQL, the following works: 在SQL中,以下工作原理:

 SELECT stuff
 FROM Table1 t1
 Inner Join Table2 t2 on t1.ID = t2.ID and t2.Weird = CAST(t1.Weird AS varchar(11))

Now in order to join on multiple columns in LINQ, I know I must do the following: 现在,为了加入LINQ中的多个列,我知道我必须执行以下操作:

var queryResult = (from o in T1)
join p in t2 on new { T1.ID, T1.Weird} equals new {T2.ID, T2.Weird}

Problem with that is that naturally I get a "Type Inference Failed" error. 问题在于,我自然会收到“类型推断失败”错误。 Makes sense, Column Weird is a string in one table and int in another. 合理,Column Weird是一个表中的字符串,而另一个表中的int。

Now generally with only one column this would be an easy fix, just do a ToString() or even SqlFunctions.StringConvert the integer field like so: 现在通常只有一列,这将是一个简单的解决方法,只需执行ToString()甚至SqlFunctions.StringConvert这样的整数字段即可:

var queryResult = (from o in T1)
join p in t2 on T1.ID equals SqlFunctions.Convert(T2.ID)

That works just fine. 那很好。 However, when I try to combine the two approaches, I get a "Invalid anonymous type member declarator" with the following: 但是,当我尝试将两种方法结合在一起时,将得到一个“无效的匿名类型成员声明器”,其内容如下:

var queryResult = (from o in T1)
join p in t2 on new { T1.ID, T1.Weird} equals new {T2.ID, SqlFunctions.Convert( T2.Weird)}

After some research I found I needed to name the values, so I tried the following: 经过研究后,我发现需要命名这些值,因此尝试了以下操作:

var queryResult = (from o in T1)
join p in t2 on new {ID = T1.ID, Weird = T1.Weird} equals new {ID = T2.ID, Weird = SqlFunctions.Convert(T2.Weird)}

This tells me the call to the SqlFunctions function is ambiguous. 这告诉我对SqlFunctions函数的调用是不明确的。 I'm kind of out of thoughts and figured I may be going to far down one road when the answer is right out in front of me. 我有点儿无所适从,并且想出当答案就在我眼前时,我可能会走的很远。 Any idea how I can make that fairly basic SQL statement in LINQ work? 知道如何在LINQ中使该基本SQL语句起作用吗?

Why don't you use .ToString() as you mentioned: 您为什么不使用.ToString()呢?


var queryResult = 
from o in T1 
join p in T2 
   on new {ID = T1.ID, Weird = T1.Weird} equals new {ID = T2.ID, Weird = T2.Weird.ToString()}

That should do the trick. 这应该够了吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM