Linq to sql 一种使用计数检索记录的好(优雅)方法

Linq to sql 一种使用计数检索记录的好(优雅)方法,linq-to-sql,data-access-layer,data-access,Linq To Sql,Data Access Layer,Data Access,上下文:ASP.NET MVC 2.0、C#、SQL Server 2008、IIS7 我在数据库中有“scheduledMeetings”表。 存在一对多关系:scheduledMeeting->meetingRegistration 这样你就可以有10个人登记参加一个会议。 meetingRegistration有字段Name和Gender(例如) 我的网站上有一个“日历视图”,显示所有即将到来的活动,以及每个活动的性别统计 目前,我使用Linq to Sql来提取数据: var meeti

上下文:ASP.NET MVC 2.0、C#、SQL Server 2008、IIS7

我在数据库中有“scheduledMeetings”表。 存在一对多关系:scheduledMeeting->meetingRegistration 这样你就可以有10个人登记参加一个会议。 meetingRegistration有字段Name和Gender(例如)

我的网站上有一个“日历视图”,显示所有即将到来的活动,以及每个活动的性别统计

目前,我使用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)
    });
(实际查询长度为半页) 因为存在匿名类型使用,我无法将其提取到一个方法中(因为我有几种不同风格的日历视图,每种视图都有不同的信息,我不想为每种视图创建新类)

对如何改进这一点有什么建议吗? 答案是数据库视图吗? 还是继续创建命名类型

欢迎任何反馈/建议。我的数据层是巨大的,我想修剪它,只是不知道如何


指向好的阅读的指针也很好。

我想通过添加两个属性来扩展您的
会议
类:

public partial class Meeting
{
    #region Properties
    public int BoyCount { get; set; }

    public int GirlCount { get; set; }
    #endregion
}
延迟加载时:

var items = db.Meetings.Select(
    m => new {
        Meeting = m,
        Girls = m.Registrations.Count(r => r.Gender == 0),
        Boys = m.Registrations.Count(r = >r.Gender == 1)
    }).ToList();

items.ForEach(i =>
{
    i.Meeting.BoyCount = i.Boys;
    i.Meeting.GirlCount = i.Girl;
});

List<Meeting> = items
    .Select(i => i.Meeting)
    .ToList();
在这种情况下,上面的部分类属性将成为getter:

public partial class Meeting
{
    #region Properties
    public int BoyCount 
    { 
        get
        {
            return this.Registrations
                .Count(r => r.Gender == 1);
        }
    }

    public int GirlCount
    {
        get
        {
            return this.Registrations
                .Count(r = > r.Gender == 0);
        }
    }
    #endregion
}
public partial class Meeting
{
    #region Properties
    public int BoyCount 
    { 
        get
        {
            return this.Registrations
                .Count(r => r.Gender == 1);
        }
    }

    public int GirlCount
    {
        get
        {
            return this.Registrations
                .Count(r = > r.Gender == 0);
        }
    }
    #endregion
}