简体   繁体   中英

C# Linq query where Table A column is not equal/doesnt math Table B column join

I have an issue with ac# linq query where I use the != operator, it works well in SQL but when I write the same query in C# it returns a different result, which is the correct way to the the results where table a column doesn't match table b column. Please see my sql query below and then my c# query.

SELECT tba.ID,fa.accountnumber,tba.Account_Number,fa.new_legalname,tba.Legal_Name,fa.new_deliverystatusname, fa.new_deliverystatus,tba.Delivery_Charge
      FROM [CRM_Embrace_Integration].[dbo].[CRM_Tarsus_Debtors_Accounts] tba
      inner join CRM_MBT_GROUP.dbo.FilteredAccount fa
      ON fa.accountnumber collate database_default   = tba.Account_Number
      where fa.new_legalname collate database_default != tba.Legal_Name

and the Linq query looks like this

var sqlJoinQuery = from accCRM in todaysCRMAccounts
                                   join accSQL in todaysCRMViewAccounts
                                   on accCRM.Account_Number equals accSQL.accountnumber
                                   where accCRM.Legal_Name != accSQL.new_legalname
                                   select new { accCRM.Legal_Name, accSQL.new_legalname };

The SQL query returns the correct result as I want where legal_name(table A) is not equals to legal_name(table B) is the other table.

The Linq query return incorrect result, please assist.

I suggest to try the following Linq as you want the data that aren't in table 2:

var result1 = (from m in db1.Table1
               select m).ToList();

var result2 = (from m in db2.Table2
               select m).ToList(); 

var finalResult = (from m in result1
                   where !(from k in result2
                   select k.Id).Contains(m.Id)
                   select m).ToList();

The above will return that aren't in Table2. I hope, this is what you wanted.

Your SQL shows you asking for where they are equal. The LINQ shows you asking for when they are not equal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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