【发布时间】:2020-06-16 03:10:00
【问题描述】:
我想提供一份约会清单以及他们各自的参与者和/或主题。
Planner 模型如下:
public class Planner : BaseEntity
{
public int? ProjectCandId { get; set; }
public int? CandidateId { get; set; }
public int? ProjectId { get; set; }
public int? CustomerId { get; set; }
public DateTime PlanDatum { get; set; }
public string Location { get; set; }
public string Description { get; set; }
public virtual Customer Customer { get; set; }
public virtual Candidate Candidate { get; set; }
public virtual Project Project { get; set; }
public virtual ProjectCand ProjectCand { get; set; }
}
我只需要从客户、项目和候选人中选择数量的字段,所以我创建了一个控制器,如下所示:
public async Task<IActionResult> Index()
{
var afspraken = await _context.Planner
.Include(c => c.Customer)
.Include(c => c.Project)
.Include(c => c.Candidate)
.Select(s => new { s.Id, s.CandidateId, s.CustomerId, s.Description, s.IsDeleted, s.Location, s.PlanDatum,
s.Customer.CompanyName,
s.Project.ProjectTitle,
s.Candidate.FullName })
.ToListAsync().ConfigureAwait(false);
return View(afspraken);
}
在我看来我使用@model IEnumerable<MyProject.Models.Planner>。
当不在控制器中应用 .Select-line 时,一切正常,但使用它会产生以下错误:
InvalidOperationException:传递到 ViewDataDictionary 的模型项的类型为 'System.Collections.Generic.List
1[<>f__AnonymousType710[System.Int32,System.Nullable1[System.Int32],System.Nullable1[System.Int32],System.String,System .Boolean,System.String,System.DateTime,System.String,System.String,System.String]]',但是这个 ViewDataDictionary 实例需要一个类型为'System.Collections.Generic.IEnumerable`1[BeagleNoseV3.Models .Planner]'。
我曾尝试创建一个 ViewModel,但这只会使事情变得更加复杂。我想使用 .Select 创建更高效的查询,但我被卡住了。
有什么想法吗?
编辑 ViewModel 场景
我已经尝试过 ViewModel 方法,但是我在如何将 VModel 链接到类方面遇到了困难。
我创建了PlannerVM 和PlanVMList:
public class PlannerVM : BaseEntityVM //BaseEntityVM provides Id, IsDeleted and some other administrative elements
{
public int? ProjectCandId { get; set; }
public int? CandidateId { get; set; }
public int? ProjectId { get; set; }
public int? CustomerId { get; set; }
public DateTime PlanDatum { get; set; }
public string Location { get; set; }
public string Description { get; set; }
public string CandidateFullName { get; set; }
public string ProjectCode { get; set; }
public string ProjectTitle { get; set; }
public string CompanyName { get; set; }
}
public class PlanVMList
{
public List<PlannerVM> AppointList { get; set; }
}
我未能在 PlannerController 中提供正确的代码来将 ViewModel 链接到我的数据集 afspraken。有什么想法吗?
【问题讨论】:
-
查看模型是要走的路。这怎么会“让事情变得更加复杂”?
-
我正在努力让 ViewModel 方法发挥作用。我将在我的问题中添加一个编辑部分来解释。
标签: sql linq asp.net-core entity-framework-core