c# - 绑定列表从模型到视图模型
问题描述
我正在尝试将 List 从模型绑定到 viewModel
这是我的模型:
public class Instruction
{
public int ID { get; set; }
public List<string> Target { get; set; }
public bool Delete { get; set; }
public List<string> DeleteLines { get; set; }
public string SpecificLine { get; set; }
public Insert InsertType { get; set; }
public string Insert { get; set; }
public MigrationPart? Part { get; set; }
}
视图模型是相同的。我正在尝试像这样绑定它:
var instructions = myDbContext.Instructions;
var model = instructions.Select(i => new InstructionView
{
Target = i.Target,
Delete = i.Delete,
DeleteLines = i.DeleteLines,
SpecificLine = i.SpecificLine,
InsertType = i.InsertType,
Insert = i.Insert,
Part = i.Part
});
return View("MigrationsList", model);
但是,当我尝试显示它时,出现错误:
The specified type member 'Target' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported
什么是正确的方法?
解决方案
首先具体化查询:
var instructions = myDbContext.Instructions.ToList();
ToList
实际上将所有数据库记录都带入内存。之后,您将在 Entity 和 ViewModel 之间进行映射。
如果不添加ToList
,Select
实际上是在尝试翻译成 SQL。由于 Entity Framework 生成的 SQL 查询无法获取整数列表并将其映射到您的类中,因此会引发该异常。
推荐阅读
- swift - 如何禁用用于应用内购买的按钮,而不将其放入另一个线程?
- sql - 根据周数,月和年sql获取周周期
- reactjs - 错误:使用 React 本机下拉选择器从数组中访问值时 item.label.substr 不是函数
- c++ - 调试器不会显示指向的变量
- mysql - 在mysql中将多行合并在一列中?当具有不同值的相同 ID 时
- vba - VBA查询CSV中的字段内容
- java - 如何使用不同类型的堆栈调用需要参数类型 int 的方法
- c++ - 在 Linux Ubuntu 上编译 googleliquidfun 时出错
- javascript - 如何在 JavaScript 的 innerHtml 中隐藏元素?
- count - BIRT 中的聚合工具:在表格列上显示类似计数的数字