首页 > 解决方案 > 绑定列表从模型到视图模型

问题描述

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

什么是正确的方法?

标签: c#asp.net

解决方案


首先具体化查询:

var instructions = myDbContext.Instructions.ToList();

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

如果不添加ToListSelect实际上是在尝试翻译成 SQL。由于 Entity Framework 生成的 SQL 查询无法获取整数列表并将其映射到您的类中,因此会引发该异常。


推荐阅读