对于复杂的查询来说,编写LINQ查询是不是很容易?
select a.sNavID,
a.sNavText,
a.sNavText as EName,
' '+a.sNavText as NameDisplay
from ContentPageNav as a
where a.navID=0
union
select b.sNavID,
a.sNavText + ' >> ' + b.sNavText as Name,
b.sNavText as EName,
' ' + b.sNavText as NameDisplay
from ContentPageNav as a
inner join ContentPageNav as b on a.sNavID=b.navID and b.catNo=1
union
select c.sNavID,a.sNavText + ' >> ' + b.sNavText + ' >> ' + c.sNavText as Name,
c.sNavText as EName,
' ' + c.sNavText as NameDisplay
from ContentPageNav as a
inner join ContentPageNav as b on a.sNavID=b.navID and b.catNo=1
inner join ContentPageNav as c on b.sNavID=c.navID and c.catNo=2
答案 0 :(得分:3)
LINQ几乎可以处理和查询你想要抛出它。
...完全组合的查询...
var query = (
from a in ContentPageNav
where a.navID == 0
select new
{
a.sNavID,
Name = a.sNavText,
EName = a.sNavText,
NameDisplay = " " + a.sNavText,
}).Concat(
from a in ContentPageNav
join b in ContentPageNav on a.navID equals b.navID
where b.catNo == 1
select new
{
b.sNavID,
Name = a.sNavText + " >> " + b.sNavText,
EName = b.sNavText,
NameDisplay = " " + b.sNavText,
}).Concat(
from a in ContentPageNav
join b in ContentPageNav on a.navID equals b.navID
where b.catNo == 1
join c in ContentPageNav on b.navID equals c.navID
where b.catNo == 1
select new
{
c.sNavID,
Name = a.sNavText + " >> " + b.sNavText + " >> " + c.sNavText,
EName = c.sNavText,
NameDisplay = " " + c.sNavText,
});
...这是一个已经分解成较小部分的版本......
var rootRecords = ContentPageNav.Where(r => r.navID == 0);
var cat1Records = ContentPageNav.Where(r => r.catNo == 1);
var cat2Records = ContentPageNav.Where(r => r.catNo == 2);
var rootComposed =
from a in rootRecords
select new
{
a.sNavID,
Name = a.sNavText,
EName = a.sNavText,
NameDisplay = " " + a.sNavText,
};
var cat1Composed =
from a in rootRecords
join b in cat1Records on a.navID equals b.navID
select new
{
b.sNavID,
Name = a.sNavText + " >> " + b.sNavText,
EName = b.sNavText,
NameDisplay = " " + b.sNavText,
};
var cat2Composed =
from a in rootRecords
join b in cat1Records on a.navID equals b.navID
join c in cat2Records on b.navID equals c.navID
select new
{
c.sNavID,
Name = a.sNavText + " >> " + b.sNavText + " >> " + c.sNavText,
EName = c.sNavText,
NameDisplay = " " + c.sNavText,
};
var composedQuery = rootComposed.Concat(cat1Composed).Concat(cat2Composed);
答案 1 :(得分:1)
您刚刚使用了SQL anti-pattern #1。
对于复杂的查询来说,编写LINQ查询是不是很容易?
当使用Linq进行数据访问时,人们倾向于编写简单的查询来完成工作。首先编写复杂查询是错误的。从这个意义上说,这是事实。 SQL也是如此。