Map 将DTO映射到实体模型

Map 将DTO映射到实体模型,map,metadata,dto,entity-framework-6,Map,Metadata,Dto,Entity Framework 6,我有一个基于MVC5的网络项目。我使用ado实体模型数据库首先与EF6。 根据我的模型,我有以下T4生成的类 namespace Mvc5.Models { using System; using System.Collections.Generic; public partial class Department { public Department() { this.Employee2 = new H

我有一个基于MVC5的网络项目。我使用ado实体模型数据库首先与EF6。 根据我的模型,我有以下T4生成的类

namespace Mvc5.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Department
    {
        public Department()
        {
            this.Employee2 = new HashSet<Employee2>();
        }

        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Employee2> Employee2 { get; set; }
    }
}
问题是当我尝试使用DepartmentTotals作为模型添加此方法的强类型视图时

我得到以下错误

错误:运行所选代码生成器时出错 无法检索部门总计的元数据


如何将部门总计映射为数据传输对象我是否需要停止t4生成或使用旧对象。因此,我可以使用此DTO查询数据库模型

何时出现异常?是在执行查询时,还是在呈现视图时,还是在实际尝试向项目添加新视图时?最后一种情况与EF无关,它更多的是关于ASP.NET MVC的工具。我相信克服这一问题的唯一方法是使用遗留对象而不是T4模板,所以我只是添加了DTO作为模型enity。
namespace Mvc5.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Employee2
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }
        public Nullable<int> DepartmentId { get; set; }

        public virtual Department Department { get; set; }
    }
}

And I have a DTO Class not Mapped to Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Mvc5.Models
{
    public class DepartmentTotals
    {
        public string Name { get; set; }
        public int Totals { get; set; }
    }
}
public ActionResult EmployeesByDepartment()
{
    var departmentTotals = db.Employee2.Include("Department")
                                       .GroupBy(x => x.Department.Name)
                                       .Select(y => new DepartmentTotals
                                       {
                                           Name = y.Key,
                                           Totals = y.Count()
                                       }).ToList();
    return View(departmentTotals);
}