LINQ:不能转换为SQL [英] LINQ: No Translation to SQL

查看:90
本文介绍了LINQ:不能转换为SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能解释为什么示例#1失败并显示不转换为SQL"并且示例#2可以正常工作吗?

Can you explain why example #1 fails with "No Translation to SQL" and example #2 works fine?

全部在存储库中:

EX#1:

public DomainPerson GetBestPerson()
{       
       var person= GetPeople().Where(p=>p.Quality=="Best").SingleOrDefault();
       return person;
}

public IQueryable<DomainPerson> GetPeople()
{
       var people= from p in Data.Persons
                   select MapToDomain(p);

       return people;
}

private DomainPerson MapToDomain(Data.Person dataPerson)
{   
       DomainPerson domainPerson= new DomainPerson{
                                  Id=dataPerson.Id,
                                  Name=dataPerson.Name,
                                  Quality=dataPerson.Quality,
                                  };
       return domainPerson;
}  

EX#2

 public DomainPerson GetBestPerson()
{       
       var person= GetPeople().Where(p=>p.Quality=="Best").SingleOrDefault();
       return person;
}

public IQueryable<DomainPerson> GetPeople()
{
       var people= from p in Data.Persons
                   select new DomainPerson{
                   Id=dataPerson.Id,
                   Name=dataPerson.Name,
                   Quality=dataPerson.Quality,
                   };


       return people;
}

推荐答案

首先,由GetPeople()生成的表达式树包含MapToDomain,无法将其转换为SQL表达式.

In the first, the expression tree produced by GetPeople() contains MapToDomain, which can't be converted to a SQL expression.

请考虑更改MapToDomain,以便它返回一个IQueryable<>(*并修复对MapToDomain()的其余调用,因此它们将调用SingleOrDefault().比解释的操作更容易,我没有编译它,因为我没有底层的可用的对象:

Consider changing MapToDomain so it returns an IQueryable<> (*and fix the remaining calls to MapToDomain(), so they call SingleOrDefault(). Easier done than explained, I did not compile this as I don't have the underlying objects available:

    public DomainPerson GetBestPerson()
    {       
           var person= GetPeople().Where(p=>p.Quality=="Best").SingleOrDefault();
           return person;
    }

    public IQueryable<DomainPerson> GetPeople()
    {
           return MapToDomain(Data.Persons);
    }

    IQueryable<DomainPerson> MapToDomain(IQueryable<Person> persons)
    {
        return persons.select(dataPerson => new DomainPerson{
                                      Id=dataPerson.Id,
                                      Name=dataPerson.Name,
                                      Quality=dataPerson.Quality,
                                      };
    }

这篇关于LINQ:不能转换为SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆