2014-01-07 146 views
5

如何在实体框架中使用替换方法。我使用下面的代码,但遇到错误。LINQ to Entities不能识别Replace方法?

using (SepasProjectEntities sp=new SepasProjectEntities()) 
{ 
var query = (from p in sp.HISAccidentLocationMappings 
         where p.Name.Replace('y','x').Contains(txt1.Text) 
         select p 
          ).ToList(); 
} 

An exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll but was not handled in user code

Additional information: LINQ to Entities does not recognize the method 'System.String Replace(Char, Char)' method, and this method cannot be translated into a store expression.

+0

我应该为'replace'方法做些什么? –

+0

@RaymondMorphy检查我的答案。 – Kehlan

回答

9

我通常使用LINQ查询的其他格式,如:

using (SepasProjectEntities sp = new SepasProjectEntities()) 
{ 
    var query = sp.HISAccidentLocationmappings 
        .Where(p => p.Name != null 
         && p.Name 
          .Replace("y", "x") 
          .Contains(txt1.Text)) 
        .ToList(); 
} 

Replace(char, char)不会工作,但Replace(string, string)意志。 Contains(string)也应该有效。

+0

以这种方式,您将从数据库加载所有HISAccidentLocationmappins对象,然后在服务器端对其进行过滤。例如,如果DB中的表有10000条记录,WHERE将只过滤5条记录,那么所有的10000条记录将被加载到应用程序,这是一个巨大的资源浪费。 –

+0

@SergeyLitvinov OP正试图在LINQ查询中使用'Replace()'和'Contains()'方法。我不认为他有很多其他选择。 – Kehlan

+0

我得到这个错误:'在App_Web_bmikir7o.dll中发生了类型'System.NullReferenceException'的异常,但没有在用户代码中处理' –

11

基于this MSDN article包含由实体框架支持的方法列表 - 只有一个替换具有支持方法的重载,这是

System.String Replace(String oldValue, String newValue) 

而且不

System.String Replace(char oldValue, char newValue) 

,你是使用。尝试从

Name.Replace('y','x') 

与字符串版本来替换它

Name.Replace("y","x") 

我没有尝试,但是从文档基于它应该工作

+0

根据那篇文章 - Contains(string val)方法也受EF –

1

可以翻转它周围?因此,我问你是否可以对txt1.Text值进行替换(并将其存储在本地变量中),然后将其与数据库中的值进行比较(我相当确信String.Contains IS只要你使用单个参数重载)。

+0

支持我原本有这个想法,但后来才意识到'Contains()'实际上是由LINQ to Entities支持的。 – Kehlan

+0

错误是关于'替换'不'包含'。我认为@SergeyLitvinov有最好的答案:支持'Replace'的某些重载,OP正在调用一个不是的。 –

+0

他的回答和我的经历在编辑之后几乎是一样的:p – Kehlan

相关问题