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

时间:2017-05-31 16:35:44

标签: c# entity-framework-core foreign-key-relationship

在我们的ASP.NET Core 1.1 EF Core 1.1 app中,我们提供了类似于以下内容的方案:父表PT和子表CH具有1-1 FK-关系。我们需要从PT表中的某些记录中获取几列,并从CH表中的相关记录中获取几列。 问题:我们如何将这些记录加载到逗号分隔的字符串中?以下代码将这些相关记录加载到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; }
}

视图模型:

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;}
....
}

控制器:此处需要加载到逗号分隔的字符串

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

1 个答案:

答案 0 :(得分:1)

使用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);