C# EF核心:将相关数据加载到字符串中
在我们的C# EF核心:将相关数据加载到字符串中,c#,entity-framework-core,foreign-key-relationship,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
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; }
}
public class CH
{
Public int CHCol1 {get; set;}
Public string CHCol2 {get; set;}
....
public int? PTId { get; set; }
public PT pt { get; set; }
}
CH:
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; }
}
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();
使用linq创建实体:
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);
我已将你的回答标记为答案。您可能需要在
string.Format(“{0},{1}”,p.PTCol1,p.CHCol1”)中添加换行符\n
代码>你的代码。谢谢