L2S System.DateTime 不支持翻译成 SQL

L2S System.DateTime has no supported translation to SQL

我的数据服务有 IQueryable 类型的方法,我的控制器正在尝试转换日期时间,但我收到此错误。任何帮助都会很棒。

错误

Method 'System.String ToCommonDateString(System.Nullable`1[System.DateTime])' has no supported translation to SQL.

数据服务

    public IQueryable<TemplatesJoinAgent> GetTemplateAgentKeyDiseaseId(Guid? agentKey, Guid? diseaseId)
            {
                //Common part
                var TemplatesJoinAgent = (from t in UnitOfWork.GetRepository<Template>().Get(t => t.IsCurrentVersion && t.Status == (short)TemplateMode.Published)
                                          join r in UnitOfWork.GetRepository<Regimen>().Get() on t.Id equals r.TemplateId
                                          join rp in UnitOfWork.GetRepository<RegimenPart>().Get() on r.Id equals rp.RegimenId
                                          join re in UnitOfWork.GetRepository<RegimenEntry>().Get() on rp.Id equals re.RegimenPartId
                                          join a in UnitOfWork.GetRepository<Agent>().Get() on re.AgentVersionKey equals a.VersionKey
                                          select new TemplatesJoinAgent
                                          {
                                              TemplateId = t.TemplateId,
                                              TemplateTitle = t.Title,
                                              GroupTitle = t.GroupTitle,
                                              GuideLineTitle = t.GuideLineTitle,
                                              ExternalDiseaseId = t.ExternalDiseaseId,
                                              DiseaseName = t.DiseaseName,
                                              VersionKey = t.VersionKey,
                                              AgentRxNormTallMan = a.RxNormTallMan,
                                              AgentNccnTallMan = a.NccnTallMan,
                                              AgentName = a.Name,
                                              AgentVersionKey = a.VersionKey,
                                              Added = t.Added,
                                              Modified = t.Modified,
                                              Indication = t.Indications,
    
    
                                          });
    
                TemplatesJoinAgent = TemplatesJoinAgent.Distinct();
    
                return TemplatesJoin
}

控制器

 PublishedDate = (t.Modified ?? t.Added).ToCommonDateString(),


public static string ToCommonDateString(this DateTime? d)
{
    return (d.HasValue ? d.Value.ToCommonDateString() : "N/A");
}

引擎不知道如何将您的自定义函数转换为 SQL。解决这个问题的最简单方法是在使用自定义函数的投影之前添加一个 AsEnumerable()。这会将上下文从 SQL 更改为内存中并允许自定义函数。

风险在于您要确保在调用 AsEnumerable() 之前执行了尽可能多的过滤器,否则您将退缩比你需要的更多的数据和内存中的过滤。当然,如果您的 过滤器 需要自定义函数,那么您要么必须接受它,要么将您的过滤器更改为 SQL 兼容。