简体   繁体   English

装订清单 <string> 从模型到视图模型

[英]Binding List<string> from model to viewModel

I am trying to bind List from model to viewModel 我正在尝试将List从模型绑定到viewModel

Here is my model: 这是我的模型:

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

The view model is identical. 视图模型是相同的。 I am trying to to bind it like this: 我试图这样绑定它:

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

However, when I try to display it I get the error: 但是,当我尝试显示它时,出现错误:

The specified type member 'Target' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

What is the right approach to this? 什么是正确的方法?

Materialize the query first: 首先实现查询:

var instructions = myDbContext.Instructions.ToList();

ToList actually brings all your database records into memory. 实际上, ToList将所有数据库记录带入内存。 After that, you are making the mapping between the Entity and ViewModel. 之后,您将在Entity和ViewModel之间进行映射。

If you do not add ToList , the Select is actually trying to be translated into SQL. 如果不添加ToList ,则Select实际上试图转换为SQL。 Since a SQL query generated by Entity Framework cannot get a list if integers and map it into your class, that exception is thrown. 由于Entity Framework生成的SQL查询无法获取整数列表并将其映射到您的类中,因此将抛出该异常。

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

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