代码之家  ›  专栏  ›  技术社区  ›  THX-1138

一种很好的(优雅的)方法来检索带有计数的记录

  •  3
  • THX-1138  · 技术社区  · 15 年前

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

    数据库中有“scheduledMeetings”表。 这样你就可以有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)
        });
    

    (实际查询长度为半页)

    还是继续创建命名类型?

    一本好书的指针也不错。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Oleks    15 年前

    我会延长你的假期 Meetings

    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();
    

    对于快速加载,解决方案之一是加载 Registrations 用你的 Meeting 实体:

    DataLoadOptions loadOptions = new DataLoadOptions();
    loadOptions.LoadWith<Meeting>(m = > m.Registrations);
    db.LoadOptions = loadOptions;
    

    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
    }