ann*_*lie 111 .net linq linq-to-entities entity-framework specification-pattern
尝试执行linq查询时出现以下错误:
LINQ to Entities无法识别方法'Boolean IsCharityMatching(System.String,System.String)'方法,并且此方法无法转换为商店表达式.
我已经阅读了很多以前的问题,人们会得到相同的错误,如果我理解正确,那是因为LINQ to Entities需要将整个linq查询表达式转换为服务器查询,因此你不能调用外部方法在里面.我无法将我的场景转换成有效的东西,我的大脑开始融化,所以我希望有人能指出我正确的方向.我们正在使用实体框架和规范模式(我对两者都是新手).
这是使用规范的代码:
ISpecification<Charity> specification = new CharitySearchSpecification(charityTitle, charityReference);
charities = charitiesRepository.Find(specification).OrderBy(p => p.RegisteredName).ToList();
Run Code Online (Sandbox Code Playgroud)
这是linq表达式:
public System.Linq.Expressions.Expression<Func<Charity, bool>> IsSatisfied()
{
return p => p.IsCharityMatching(this.charityName, this.charityReference);
}
Run Code Online (Sandbox Code Playgroud)
这是IsCharityMatching方法:
public bool IsCharityMatching(string name, string referenceNumber)
{
bool exists = true;
if (!String.IsNullOrEmpty(name))
{
if (!this.registeredName.ToLower().Contains(name.ToLower()) &&
!this.alias.ToLower().Contains(name.ToLower()) &&
!this.charityId.ToLower().Contains(name.ToLower()))
{
exists = false;
}
}
if (!String.IsNullOrEmpty(referenceNumber))
{
if (!this.charityReference.ToLower().Contains(referenceNumber.ToLower()))
{
exists = false;
}
}
return exists;
}
Run Code Online (Sandbox Code Playgroud)
如果您需要更多信息,请与我们联系.
非常感谢,
Annelie
Str*_*ior 115
正如您所知,实体框架实际上无法将C#代码作为其查询的一部分运行.它必须能够将查询转换为实际的SQL语句.为了使其工作,您必须将查询表达式重组为Entity Framework可以处理的表达式.
public System.Linq.Expressions.Expression<Func<Charity, bool>> IsSatisfied()
{
string name = this.charityName;
string referenceNumber = this.referenceNumber;
return p =>
(string.IsNullOrEmpty(name) ||
p.registeredName.ToLower().Contains(name.ToLower()) ||
p.alias.ToLower().Contains(name.ToLower()) ||
p.charityId.ToLower().Contains(name.ToLower())) &&
(string.IsNullOrEmpty(referenceNumber) ||
p.charityReference.ToLower().Contains(referenceNumber.ToLower()));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
110562 次 |
| 最近记录: |