LINQ project() 在 LINQ IQueryable 中自动从数据实体映射到业务实体?

LINQ project() to automap from data entity to business entity within LINQ IQueryable?

我不确定这是否可行。

一些要求

这就是我们正在尝试做的事情

var query = from mpg in this.markingPeriodGroupRepository.GetAll()
            join mp in this.markingPeriodRepository.GetAll().Include(x => x.SchoolMarkingPeriods) 
                on mpg.MarkingPeriodGroupID equals mp.MarkingPeriodGroupID
            select new MarkingPeriodTerm
            {
                MarkingPeriodGroupID = mpg.MarkingPeriodGroupID,
                MarkingPeriodGroupName = mpg.MarkingPeriodGroupName,
                SchoolMarkingPeriods = mp.SchoolMarkingPeriods.AsQueryable()
                    .Project().To<SchoolMarkingPeriod>(null).ToList()
            };

在 运行 时,我们得到这个错误:

LINQ to Entities does not recognize the method 'System.Linq.IQueryable1[NHA.App.Core.v2.Business.Models.SchoolMarkingPeriod] To[SchoolMarkingPeriod](System.Collections.Generic.IDictionary2[System.String,System.Object])' method, and this method cannot be translated into a store expression.

是否可以在此 IQueryable 中自动映射此 属性?

在您的查询中,select 一个匿名类型并且还没有执行 Project 方法。

var query = from mpg in this.markingPeriodGroupRepository.GetAll()
            join mp in this.markingPeriodRepository.GetAll().Include(x => x.SchoolMarkingPeriods)
                on mpg.MarkingPeriodGroupID equals mp.MarkingPeriodGroupID
            select new //Here we are selecting an anonymous type
            {
                MarkingPeriodGroupID = mpg.MarkingPeriodGroupID,
                MarkingPeriodGroupName = mpg.MarkingPeriodGroupName,
                SchoolMarkingPeriods = mp.SchoolMarkingPeriods   
            };

然后,执行查询后,我们就可以使用Project方法了。

var result = query
    .ToList() //This will actually execute the query.
    .Select(x => new MarkingPeriodTerm()
    {
        MarkingPeriodGroupID = x.MarkingPeriodGroupID,
        MarkingPeriodGroupName = x.MarkingPeriodGroupName,
        SchoolMarkingPeriods = x.SchoolMarkingPeriods.Project().To<SchoolMarkingPeriod>(null).ToList() //Here we are executing the Project method on in-memory data
    });