我尝试转换此sql查询
Select *
from (
select SenDa.*,Prod.ProductKHK,FCod.FailCodeDesc
from databa.dbo.SensorData as SenDa
left join Products as Prod on SenDa.ProductID = Prod.ProductID
left join FailCodes as FCod on SenDa.FailCode = FCod.FailCode and (FCod.ProdLineID =0 or FCod.ProdLineID = FCod.ProdLineID)
) as SenDa
到sql Linq所以:
var SensDatJoinFail = (from SensDat in Jas_en.SenDatas
join Prod in Jas_en.Products on
SensDat.ProductID equals Prod.ProductID
join FCod in Jas_en.FailCodes on SensDat.FailCode equals FCod.FailCode1
where FCod.ProdLineID == 0 || FCod.ProdLineID == FCod.ProdLineID
select new
{
Serial_No = SensDat.Serial_No,
OrderID = SensDat.OrderID,
Artikelnummer = Prod.ProductKHK,
StartProcTime = SensDat.StartProcTime,
EndProcTime = SensDat.EndProcTime,
Packaged = SensDat.Packaged,
Labeled = SensDat.Labeled,
Reworked = SensDat.Reworked,
LastStation = SensDat.LastStation,
FailCode = SensDat.FailCode,
FailCodeDesc = FCod.FailCodeDesc,
});
但我在行数
中查询结果有所不同我不知道,问题出在哪里?
答案 0 :(得分:2)
这是EF常见问题解答。不要在LINQ to Entitites中使用JOINS。只需导航您的导航属性。类似的东西:
from SensDat in Jas_en.SenDatas
select new
{
Serial_No = SensDat.Serial_No,
OrderID = SensDat.OrderID,
Artikelnummer = SensDat.Product.ProductKHK,
StartProcTime = SensDat.StartProcTime,
EndProcTime = SensDat.EndProcTime,
Packaged = SensDat.Packaged,
Labeled = SensDat.Labeled,
Reworked = SensDat.Reworked,
LastStation = SensDat.LastStation,
FailCode = SensDat.FailCode,
FailCodeDesc = SensDat.FailCode.FailCodeDesc,
});
答案 1 :(得分:1)
由于您使用内部加入而非左加入,因此您获得的行数减少了。尝试这样的事情:
var result= from table1 in dbo.Table1
from table2 in dbo.Table2
.Where(i=>i.Id == table1.Id)
.DefaultIfEmpty();
或者您可以查看如何Perform left outer joins
Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };
Pet barley = new Pet { Name = "Barley", Owner = terry };
Pet boots = new Pet { Name = "Boots", Owner = terry };
Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
Pet bluemoon = new Pet { Name = "Blue Moon", Owner = terry };
Pet daisy = new Pet { Name = "Daisy", Owner = magnus };
// Create two lists.
List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
List<Pet> pets = new List<Pet> { barley, boots, whiskers, bluemoon, daisy };
var query = from person in people
join pet in pets on person equals pet.Owner into gj
from subpet in gj.DefaultIfEmpty()
select new { person.FirstName, PetName = subpet?.Name ?? String.Empty };