EF将来自多个实体的数据合并为单个实体

时间:2014-09-05 18:00:08

标签: asp.net-mvc entity-framework-5

我有五个级联表,称为活动表,格式如下:

Table Schema

我想将数据合并到单个实体中,其中每个记录通过PeriodID,Activity和Site是唯一的。因此,想将它们读入以下视图模型:

public class PivotViewModel
{
    [Display(Name = "Period ID")]
    public Int32 PeriodID { get; set; }

    [Display(Name = "Site")]
    public string SiteID { get; set; }

    [Display(Name = "Product")]
    public string Product { get; set; }

    [Display(Name = "Activity")]
    public string Activity { get; set; }

    [Display(Name = "Value")]
    public double? Value { get; set; }

    [Display(Name = "Value1")]
    public double? Value1 { get; set; }

    [Display(Name = "Value2")]
    public double? Value2 { get; set; }

    [Display(Name = "Value3")]
    public double? Value3 { get; set; }

    [Display(Name = "Value4")]
    public double? Value4 { get; set; }

    [Display(Name = "Value5")]
    public double? Value5 { get; set; }
}

我不确定应该如何编写Linq查询,以便按照句点ID将所有5个表合并到同一行。我更愿意这样做,而不是使用联合查询。

当我执行以下操作时,它将覆盖最后的结果。

var activityResult = db.OMS_Planned_Receipts.Where(p => p.Product == product)
  .Select(b => new PivotViewModel
  {
      Product = b.Product,
      PeriodID = b.PeriodID,
      SiteID = b.SiteID,
      Value = b.Value,
      Activity = "Planned"
  });

activityResult = db.OMS_System_Forecast.Where(p => p.Product == product)
  .Select(b => new PivotViewModel
  {
      Product = b.Product,
      PeriodID = b.PeriodID,
      SiteID = b.SiteID,
      Value = b.Value,
      Activity = "Forecast"
  });

0 个答案:

没有答案