EF6:映射到ViewModel可重用性

时间:2014-06-12 20:20:48

标签: c# linq entity-framework entity-framework-6

使用Entity Framework 6,我在类对象和包含在类中的viewmodel对象之间有映射函数,如下所示:

public class DataMappers
{
    public static Expression<Func<Data.Models.Employer, EmployerViewModel>> EmployerMapper = (e => new EmployerViewModel()
    {
        Name = e.Name,
        Location = e.Location
        ....
    });
}

然后我可以在多个地方打电话:

            results = db.Employers.OrderBy(e => e.Name)
                                  .Select(DataMappers.EmployerMapper)
                                  .ToList();

这将生成仅包含我需要的列的SQL语句。我的问题是,如果其他表引用我的雇主&#39;那么无论如何都要重复使用它。表?即。

    public static Expression<Func<Data.Models.Person, PersonViewModel>> Person = (p => new PersonViewModel()
    {
        FirstName = p.FirstName,
        LastName = p.LastName,
        Employer = *use the 'EmployerMapper' expression above on p.Employer*
        ....
    });

可以这样做,还是我需要在这种情况下复制映射代码?

我尝试在第二个示例中使用它作为Func而不是Expression<Func>,它将编译(Employer = EmployerMapper(p.Employer)),但是,在运行时会收到The LINQ expression node type 'Invoke' is not supported in LINQ to Entities异常-time。

1 个答案:

答案 0 :(得分:5)

您必须安装LinqKit,并使用其AsExpandable()

using LinqKit;

results = db.Employers.AsExpandable()
                      .OrderBy(e => e.Name)
                      .Select(DataMappers.EmployerMapper)
                      .ToList();

你的投影功能:

using LinqKit;

public static Expression<Func<Data.Models.Person, PersonViewModel>> Person = (p => new PersonViewModel()
    {
    FirstName = p.FirstName,
    LastName = p.LastName,
    Employer = DataMappers.EmployerMapper.Invoke(p.Employer)
    });

有关LinqKit及其工作原理的更多信息here