Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

c# - select top 5 in entity framework

I have

[Person]
PersonID, EmailAddress, FirstName, LastName

[OnlineAccount]
OnlineAccountID, PersonID, Nickname

Each person is allowed to have 0-* OnlineAccount.

In entity framework with C#, how do I select the top 5 Person that has the most accounts?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

var items = context.PersonSet.OrderByDescending(u => u.OnlineAccounts.Count).Take(5);

This returns IQueryable<Person>. It doesn't return results yet, because it implements deferred execution. It will be translated to SQL and executed when needed:

var metarializedItems = items.ToList(); // ToList forces execution

or

foreach(var item in items) // foreach forces execution

Example above will translate to SQL similar to this one:

SELECT TOP 5 p.PersonID, p.EmailAddress, p.FirstName, p.LastName 
FROM Person p
ORDER BY (SELECT COUNT(*) FROM OnlineAccount oa WHERE p.PersonID = oa.PersonID) DESC

It won't be this exact SQL. Different EF version may produce different SQLs, but I wrote it to ilustrate how it works. Take(5) is translated to TOP 5. OrderByDescending(u => u.OnlineAccounts.Count) is translated to ORDER BY (SELECT COUNT(*) FROM OnlineAccount oa WHERE p.PersonID = oa.PersonID) DESC. This is power of Entity Framework. It translates .NET expressions to SQL.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...