美好的一天
我正在使用ASP。带有C#和实体框架的NET MVC。我的代码优先模型中有三个表。
public class Project
{
public Guid Id { get; set; }
public guid ProjectTypeId{ get; set; }
public string projectType{ get; set; }
[Required]
public DateTime CreationDate{ get; set; }
//more properties here
//...
public bool Activated{ get; set; }
public IList<ProjectDetail> ProjectDetails{ get; set; }
}
您会看到一个项目有很多细节。
public class ProjectDetail
{
[Required]
public Guid Id { get; set; }
public Project Project{ get; set; }
[Required]
public Guid ProjectId{ get; set; }
public string DetailDescription{ get; set; }
public IList<ProjectDetailsAnswer> ProjectDetailsAnswers{ get; set; }
}
一个projectDetail有很多答案:
public class ProjectDetailsAnswer
{
[Required]
public Guid Id { get; set; }
[Required]
public Guid ProjectDetailId{ get; set; }
public ProjectDetail ProjectDetail{ get; set; }
public string OtherField{ get; set; }
[Required]
[MaxLength(512)]
public string AnswerDescription{ get; set; }
}
我想做的是使用带有lambda表达式的实体框架来加载视图模型
public class MyViewModel
{
public Guid projectTypeId{ get; set; }
public string projectType { get; set; }
public string DetailDescription { get; set; }
public IEnumerable<string> AnswerDescription{ get; set; }//this propertie comes from ProjectDetailsAnswer.AnswerDescription
}
到目前为止,我的代码是:
var y = _dbContext.Project
.Include(a => a.ProjectDetail.Select(p => p.ProjectDetailsAnswer))
.Select(n =>new MyViewModel{projectTypeId=n.projectTypeId,projectType =n.Project.projectType,DetailDescription =n.AnswerDescription.Select(b =>b.AnswerDescription).ToList()})
.ToList();
我收到此错误:>无法在此代码中将字符串转换为List。 n.AnswerDescription.Select(b =>b.AnswerDescription).ToList()
我在做什么错?您是否可以(如果可能)为我提供一些可用于将数据加载到视图模型中的代码?
,问题来了
谢谢
答案 0 :(得分:1)
如果DetailDescription只是视图模型中的一个字符串,而不是IList,那么我想它是一个ProjectDetailViewModel,因此您的linq应该是:
var result = _dbContext.ProjectDetails //<==search from details
.Select(x => new ProjectDetailViewModel
{
projectTypeId = x.Project.ProjectTypeId,
projectType = x.Project.projectType,
DetailDescription = x.DetailDescription,
AnswerDescription = x.ProjectDetailsAnswers.Select(a => a.AnswerDescription)
}).ToList();
但是如果您坚持要从项目中查询:
var result = _dbContext.Projects.SelectMany(x=>x.ProjectDetails) //<==use SelectMany
.Select(x => new ProjectDetailViewModel
{
projectTypeId = x.Project.ProjectTypeId,
projectType = x.Project.projectType,
DetailDescription = x.DetailDescription,
AnswerDescription = x.ProjectDetailsAnswers.Select(a => a.AnswerDescription)
}).ToList();