将List <string>从模型绑定到viewModel

时间:2019-06-20 14:41:06

标签: c# asp.net

我正在尝试将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

什么是正确的方法?

1 个答案:

答案 0 :(得分:0)

首先对查询进行材料化

var instructions = myDbContext.Instructions.ToList();

ToList实际上将所有数据库记录都带入内存。之后,您将在Entity和ViewModel之间进行映射。

如果不添加ToList,则Select实际上正在尝试转换为SQL。由于Entity Framework生成的SQL查询无法获取整数列表并将其映射到您的类中,因此会抛出该异常。