检索带有计数的记录的好(优雅)方法
上下文:ASP.NET MVC 2.0、C#、SQL Server 2008、IIS7
我在数据库中有“scheduledMeetings”表。 存在一对多关系:scheduledMeeting ->会议注册 这样您就可以有 10 人注册参加会议。 MeetingRegistration 具有“名称”和“性别”字段(例如)。
我的网站上有一个“日历视图”,显示所有即将发生的事件,以及每个事件的性别计数。
目前我使用Linq to Sql来提取数据:(
var meetings = db.Meetings.Select(
m => new {
MeetingId = m.Id,
Girls = m.Registrations.Count(r => r.Gender == 0),
Boys = m.Registrations.Count(r=>r.Gender == 1)
});
实际查询有半页长) 因为存在匿名类型的使用,所以我无法将其提取到方法中(因为我有几种不同风格的日历视图,每个视图都有不同的信息,并且我不想为每个视图创建新类)。
关于如何改进这一点有什么建议吗? 数据库视图就是答案吗? 或者我应该继续创建命名类型?
欢迎任何反馈/建议。我的 DataLayer 很大,我想修剪它,只是不知道如何。
好的阅读指南也很好。
Context: ASP.NET MVC 2.0, C#, SQL Server 2008, IIS7
I have 'scheduledMeetings' table in the database.
There is a one-to-many relationship: scheduledMeeting -> meetingRegistration
So that you could have 10 people registered for a meeting.
meetingRegistration has fields Name, and Gender (for example).
I have a "calendar view" on my site that shows all coming events, as well as gender count for each event.
At the moment I use Linq to Sql to pull the data:
var meetings = db.Meetings.Select(
m => new {
MeetingId = m.Id,
Girls = m.Registrations.Count(r => r.Gender == 0),
Boys = m.Registrations.Count(r=>r.Gender == 1)
});
(actual query is half-a-page long)
Because there is anonymous type use going on I cant extract it into a method (since I have several different flavors of calendar view, with different information on each, and I don't want to create new class for each).
Any suggestions on how to improve this?
Is database view is the answer?
Or should I go ahead and create named-type?
Any feedback/suggestions are welcome. My DataLayer is huge, I want to trim it, just don't know how.
Pointers to a good reading would be good too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将通过添加 2 个属性来扩展您的
Meetings
类:使用延迟加载:
使用急切加载,解决方案之一是使用您的
Meeting
加载Registrations
code> 实体:在这种情况下,上面的部分类属性变成了 getters:
I'd extend your
Meetings
class by adding 2 properties:With deferred loading:
With eager loading, one of the solutions is to load
Registrations
with yourMeeting
entity:In this case the partial class properties above are became getters: