在列表中添加列表

时间:2015-06-05 20:59:11

标签: c# sql sql-server linq entity-framework

出于某种原因,我们被要求使用存储过程并使用Entity Framework调用此存储过程。以下是示例存储过程:

CREATE SampleStoredProcedure () AS 
    SELECT TOP 10 SiteId, SiteName, DayOfTheWeek, OpenTime, CloseTime
    FROM Sites s, BusinessHours b
    WHERE s.SiteId = b.SiteId
    Group By SiteId, SiteName, DayOfTheWeek, OpenTime, CloseTime

这些网站在具有以下SAMPLE架构的另一个桌面上有营业时间,其中一个站点可以有5个条目用于与周一到周五操作相对应的营业时间。

CREATE TABLE [dbo].[BusinessHours](
   [Id] [int] IDENTITY(1,1) NOT NULL,
   [SiteId] [int] NOT NULL,
   [DayOfTheWeek] [int] NOT NULL,
   [OpenTime] [time](7) NOT NULL,
   [CloseTime] [time](7) NOT NULL,

问题是,数据库的设计很差,因此Sites.SiteId不是主键,您不能将其作为BusinessHours.SiteId的FK引用。

现在,在服务器上,我希望有一个像这样映射的对象:

IEnumerable<SampleStoredProcedure_Result> test = dbContext.SampleStoredProcedure

我想将此SampleStoredProcedure_Result映射到类似:

Class Result {
    public int SiteId {get; set;}
    public int SiteName {get; set;}
    IEnumerable<BusinessHours> BusinessHours { get; set; }
}

我不确定除了蛮力方法之外我怎样才能有效地编码。

1 个答案:

答案 0 :(得分:0)

  

我想将此SampleStoredProcedure_Result映射到类似:

class Result {
    public int SiteId {get; set;}
    public int SiteName {get; set;}
    IEnumerable<BusinessHours> BusinessHours { get; set; } }      
}

以下是如何将SampleStorecProcedure_Result个对象的集合映射到Result个对象的集合:

IEnumerable<Result> results = data.GroupBy(x => new { x.SiteId, x.SiteName })
                                  .Select(g => new Result
                                  {
                                      SiteId = g.Key.SiteId,
                                      SiteName = g.Key.SiteName,
                                      BusinessHours = g.Select(x => new BusinessHours
                                      {
                                         DayOfTheWeek = x.DayOfTheWeek,
                                         OpenTime = x.OpenTime,
                                         CloseTime = x.CloseTime
                                      })
                                  });