简体   繁体   English

EF6:映射到ViewModel可重用性

[英]EF6: Mapping to ViewModel Reusability

Using Entity Framework 6, I have mapping functions between the Model objects and viewmodel objects contained in a class like so: 使用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
        ....
    });
}

Which I can then call in multiple places like so: 然后我可以在多个地方调用,如下所示:

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

Which will generate a SQL statement with only the columns I need. 这将生成仅包含我需要的列的SQL语句。 My question is, is there anyway to reuse this if other tables reference my 'Employer' table? 我的问题是,如果其他表引用我的'雇主'表,是否还有重用它? ie

    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*
        ....
    });

Can that be done, or will I need to duplicate that mapping code in every situation like this? 可以这样做,还是我需要在这种情况下复制映射代码?

I tried using it as just a Func instead of Expression<Func> in that second example, which would compile ( Employer = EmployerMapper(p.Employer) ), however, you receive The LINQ expression node type 'Invoke' is not supported in LINQ to Entities exception at run-time. 我尝试在第二个示例中使用它作为Func而不是Expression<Func> ,它将编译( Employer = EmployerMapper(p.Employer) ),但是,您收到The LINQ expression node type 'Invoke' is not supported in LINQ to Entities运行时The LINQ expression node type 'Invoke' is not supported in LINQ to Entities异常。

You'll have to install LinqKit , and use its AsExpandable() : 你必须安装LinqKit ,并使用它的AsExpandable()

using LinqKit;

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

And your projection function: 而你的投影功能:

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)
    });

More information on LinqKit and how it works here . 在LinqKit以及如何更多信息,它的工作原理在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM