[英]LINQ, Should I JOIN or use nested SELECT NEW's
I have to below 2 LINQ statements. 我必须低于2个LINQ语句。 They both return (seemingly) the same result set.
它们都返回(看似)相同的结果集。 Can anyone explain to me why I should use one way versus the other?
任何人都可以向我解释为什么我应该使用一种方式与另一种方式? Is it as simple as "You say potato, I say potato; you say tomato, I say tomato" ?
它就像“你说土豆,我说土豆;你说番茄,我说番茄”一样简单吗?
Here are the two flavors of LINQ --> 以下是LINQ的两种风格 - >
1) The two lets
below are to private Methods that take an ID and return the NAME. 1)这两个
lets
下面是该拿的ID,并返回名称的私有方法。
var business = from businesse in context.tblBusinesses
where businesse.BusinessID == businessID
join addresse in context.tblAddresses on businesse.BusinessID equals addresse.BusinessID
let stateName = GetStateNameByID(addresse.StateID)
let countyName = GetCountyNameByID(addresse.CountyID)
select new
{
businesse.BusinessName,
businesse.ContactName,
businesse.EmailAddress,
addresse.AddressLine1,
addresse.AddressLine2,
addresse.AddressLine3,
addresse.CityName,
State = stateName,
addresse.ZipCode,
addresse.ZipPlus,
County = countyName
};
2) 2)
var query = from businesse in context.tblBusinesses
where businesse.BusinessID == businessID
select new
{
businesse.BusinessName,
businesse.ContactName,
businesse.EmailAddress,
Address = from addresse in businesse.tblAddresses
select new
{
addresse.AddressLine1,
addresse.AddressLine2,
addresse.AddressLine3,
addresse.CityName,
State = addresse.StateID,
addresse.ZipCode,
addresse.ZipPlus,
County = addresse.tblAdminCounty
}
};
When you watch the sql server profiler, you see that the second one creates many queries but the first one gets all data in one query. 当您观察sql server探查器时,您会看到第二个创建了许多查询,但第一个查询获取了一个查询中的所有数据。 So the first one is more efficient.
所以第一个更有效率。
Are you sure they give the same result? 你确定他们给出了相同的结果吗?
It looks like the first example would flatten your Address
property into multiple properties, while your second example would have an Address
property that itself contains properties. 看起来第一个示例会将您的
Address
属性展平为多个属性,而您的第二个示例将具有一个本身包含属性的Address
属性。
But otherwise, I would say the difference between joining and an "inner select" would be a matter of personal preference. 但除此之外,我会说加入和“内部选择”之间的区别将取决于个人偏好。 I'd probably prefer to go with a join because I'm used to writing SQL and having the word
join
there makes your intent obvious. 我可能更喜欢使用连接,因为我习惯于编写SQL并且在那里使用单词
join
会使您的意图变得明显。 But I don't see a problem with using an inner select, either. 但我也没有看到使用内部选择的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.