LINQ to SQL,连接表以获得不同的结果?

时间:2016-11-30 13:09:03

标签: c# sql sql-server linq

我正在尝试编写一个LINQ查询,它将从两个SQL Server数据表中获取一些不同的值。

我有两个名为Facility_Cost_TBLTenant_Bills_TBL的表。 然后我有一个名为Nursing_Home_Name的列,我试图从中获取不同的数据。

这是我在LINQ中的努力,但它不起作用,

var name = (from f in dataContext.Facility_Cost_TBLs
                join t in dataContext.Tenant_Bills_TBLs on f.Tenant_Code equals t.Tenant_Code
                where f.Tenant_Code == code && f.Date_Month == date.Month && f.Date_Year == date.Year
                select new {Facility_Cost_TBL = f, Tenant_Bills_TBL = t}).Distinct();

这是一个有效的SQL语句,我通过T-SQL做了我想做的事。

SELECT DISTINCT Nursing_Home_Name 
         FROM (SELECT Nursing_Home_Name 
         FROM Facility_Cost_TBL 
         WHERE Date_Year = 2016 AND Date_Month = 10 AND Tenant_Code = 664250 
         UNION SELECT Nursing_Home_Name 
         FROM Tenant_Bills_TBL 
         WHERE Year_Data = 2016 AND Month_Data = 10 AND Tenant_Code = 664250) 
         a

有人可以告诉我LINQ sytax和LINQ扩展方法查询的样子吗?

2 个答案:

答案 0 :(得分:1)

请尝试以下

var names = ((from f in dataContext.Facility_Cost_TBLs 
                                          where f.Tenant_Code == "664250" && f.Date_Month == "10" && f.Date_Year == "2016"
                                          select new { Nursing_Home_Name = f.Nursing_Home_Name }).
                                          Union(
                                          from t in dataContext.Tenant_Bills_TBLs
                                          where t.Tenant_Code == "664250" && t.Date_Month == "10" && t.Date_Year == "2016"
                                          select new { Nursing_Home_Name = t.Nursing_Home_Name })).ToList();

希望这会对你有所帮助

答案 1 :(得分:1)

试试看这是否有效。 LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

var name = (from f in dataContext.Facility_Cost_TBLs
                join t in dataContext.Tenant_Bills_TBLs  equals on new { f.Tenant_Code, f.Date_Month, f.Date_Year } equals new { t.Tenant_Code, t.Date_Month, t.Date_Year } 
                where f.Tenant_Code == code && f.Date_Month == date.Month && f.Date_Year == date.Year
                select new {Facility_Cost_TBL = f, Tenant_Bills_TBL = t}).Distinct();