Code First Entity Framework,选择ViewModel - 带参数

时间:2017-01-15 20:50:17

标签: c# entity-framework linq constructor

我创建了类Employee:

public class Employees : BaseModel
{
    [Key]
    public int EmployeeId { get; set; }
   // [ohter parameter]
    public int? DepartmentId { get; set; }
    public virtual Departments Departments { get; set; }
    public int? OccupationId { get; set; }
    public virtual Occupations Occupations { get; set; }
}

我想创建一个视图模型。

public class Employee_ViewModel 
{
    public Employee_ViewModel(Employees item)
    {
        this.EmployeeId = item.EmployeeId;
        //[other parameter]
        this.DepartmentId = item.DepartmentId;
        this.OccupationId = item.OccupationId;
    }

    public int EmployeeId { get; set; }
    //[other parameter]
    public string DepartmentName { get; set; }
    public string OccupationName { get; set; }
}

我的方法返回Employee_ViewModel,如下所示:

 List<Employee_ViewModel> item = contex.Employees.Where(w => w.IsActive == true && w.IsVisible == true)
                                     .Include(i => i.Departments)
                                     .Include(i => i.Occupations)
                                     .Select(s => new Employee_ViewModel(s)
                                     {
                                         OccupationName = s.Occupations.Name,
                                         DepartmentName = s.Departments.Name
                                     })
                                     .ToList();

最后我收到错误:

  

LINQ to Entities中仅支持无参数构造函数和初始值设定项。

此帖的解决方案:

Only parameterless constructors and initializers are supported in LINQ to Entities

正在运作,但为什么我的构造函数不起作用?

1 个答案:

答案 0 :(得分:2)

与其他工具一样,Entity Framework在运行时创建模型的代理,这些代理将作为模型的派生类发出。显然,您不能指望代理生成器使用带参数的构造函数来实例化您的模型。

总结:保持简单,按照使用方式使用工具:您的实体至少应包含无参数构造函数。

考虑使用AutoMapper来保持简单

// If you go for the AutoMapper approach, you need no constructor 
// with parameters or factory method anymore!
List<Employee_ViewModel> item = contex.Employees.Where(w => w.IsActive == true && w.IsVisible == true)
                                     .Include(i => i.Departments)
                                     .Include(i => i.Occupations)
                                     .ProjectTo<EmployeeViewModel>()
                                     .ToList();

请参阅AutoMapper的文档queryable extensions,详细了解如何将其与实体框架相结合。