繁体   English   中英

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

[英]EF-Core: loading related data into a string

在带有EF Core 1.1 app ASP.NET Core 1.1 ,我们有一个类似于以下情形:父表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; }
}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM