EF-Core:加载相关数据到字符串中

EF-Core: loading related data into a string

在我们的 ASP.NET Core 1.1EF Core 1.1 app 中,我们有一个类似于以下的场景:Parent table PT 和 child table CH 有 1-1 FK-relationship。我们需要从 PT table 的某些记录中获取几列,并从 CH table 的关联记录中获取几列。 问题:我们如何将这些记录加载到逗号分隔的字符串中?以下代码将这些相关记录加载到 ViewModel.

注意: 如果我们要加载记录 - 进入逗号分隔的字符串 - 仅从 PT 加载记录,我们将执行以下操作:

string csv = string.Concat(
                 PT.Select(
                        p => string.Format("{0},{1},{2}\n", p.PTCol1, p.PTCol2, p.PTCol3)));

PT:

public class PT
{
  Public int PTId {get; set;}
  Public int PTCol1 {get; set;}
  Public string PTCol1 {get; set;}
  Public float PTCol1 {get; set;}
  ....
  public CH ch { get; set; }
}

CH:

public class CH
{
  Public int CHCol1 {get; set;}
  Public string CHCol2 {get; set;}
  ....
  public int? PTId { get; set; }
  public PT pt { get; set; }
}

ViewModel:

public class PT_CH_ViewModel
{
   Public int PTCol1 {get; set;}
   Public string PTCol1 {get; set;}
   Public float PTCol1 {get; set;}
   ....
   Public int CHCol1 {get; set;}
   Public string CHCol2 {get; set;}
....
}

Controller:这里需要加载到逗号分隔的字符串

var pts = _context.PT
                .Include(p => p.CH)
                .Where(p => p.PTcol == selectedID)
                .Select(pt => new PT_CH_ViewModel()
                {
                    PTCol1 = pt.Col1,
                    PTCol2 = pt.Col2,
                    PTCol3 = pt.Col3,
                    CHCol1 = pt.CH.Col1,
                    CHCol2 = pt.CH.Col2
                }).ToList();

使用 linq-to-entities:

var pts = (from pt in context.PT
          join ch in context.CH on pt.PTId equals ch.PTId
          select new {
              PTCol1 = pt.Col1, 
              CHCol1 = ch.CHCol1
              // select other columns here...
          }).ToList();

var ptsStringCollection = pts.Select(p => string.Format("{0},{1}", p.PTCol1, p.CHCol1);