Convert SQL query to Linq query?
I have a SQL query and i want to convert to LINQ quyery, plz help me !
SELECT TOP 10 UPER( C1.NAME)
FROM CUSTOMER C1 WHERE C1.NAME LIKE 'A%' AND C1.ID NOT IN
(SELECT TOP 20 C2.ID FROM CUSTOMER C1 WHERE C1.NA开发者_Python百科ME LIKE 'A%' ORDER BY C2.NAME)
ORDER BY C1.NAME
UPDATE
SELECT TOP 10 UPPER( C1.NAME)
FROM CUSTOMER C1 WHERE C1.NAME LIKE 'A%' AND C1.ID NOT IN
(SELECT TOP 20 C2.ID FROM CUSTOMER C2 WHERE C2.NAME LIKE 'A%' ORDER BY C2.NAME)
ORDER BY C1.NAME
The Datacontext class declared "db". Sorry about my poor english !
To me that doesn't look too complex, unless I'm reading it wrong:
var query = from c in db.Customer
where c.name.StartsWith("A")
orderby c.name
select c.name.ToUpper();
return query.Skip(20).Take(10).ToList();
A lot of people seem to be translating your SQL directly into LINQ, but it looks like they're missing the point of your compound query (and the fact that you're selecting from the same table with the same ORDER-BY). The Skip
method removes the need for the C1.ID NOT IN (SELECT TOP 20...
part, so you can do it all in one LINQ query.
One tiny note: If your database is case-insensitive (which it probably is), you might need to replace where c.name.StartsWith("A")
with where c.name.StartsWith("A", StringComparison. OrdinalIgnoreCase)
. I'm not sure about that, though; I'd try it without the StringComparison
first.
I think you got your answer, so I want to introduce a useful tools for you that enable you to converting SQL queries to LINQ queries. Its LINQPad :
Well, you don't have to! LINQPad lets you interactively query databases in a modern query language: LINQ. Kiss goodbye to SQL Management Studio!
LINQPad supports everything in C# 4.0 and Framework 4.0:
LINQ to Objects LINQ to SQL and Entity Framework LINQ to XML Parallel LINQ
var result = (from o in db.Customer
where SqlMethods.Like(o.Name, "A%")
order by i.Name
select o.Name.ToUpper()).Skip(20).Take(10);
I think there is more better way of doing this but this was all my effort...
:D
精彩评论