[英]Entity Framework - String conversion error
我收到以下错误,但是我不确定如何重写我的陈述? 有任何想法吗?
错误:
LINQ to Entities无法识别方法'System.String Convert(System.String)'方法,并且该方法无法转换为商店表达式
码:
public Client FindClientByMobile(string mobile, string accountId)
{
Client client = RepositorySet.Include("Account").FirstOrDefault(c => c.AccountId == accountId && !c.IsDeleted
&& ((Convert(c.TelephoneHome) == mobile) || (Convert(c.TelephoneMobile) == mobile) || (Convert(c.TelephoneWork) == mobile)));
return client;
}
public static string Convert(string mobile)
{
var filterNumber = from letter in mobile
where char.IsDigit(letter)
select letter;
StringBuilder number = new StringBuilder();
number.Append(filterNumber.ToArray());
return number.ToString();
}
该错误意味着Linq需要将您的表达式转换为Sql语句。 您的自定义Convert方法不可翻译,因为它是c#代码,而不是数据库服务器上也存在的某种方法。
由于您已经传递了帐户ID,因此我将假定这是唯一的,或者将其过滤到足够接近唯一的位置,以确保您不会检索到大量对象。 然后,您可以首先实现对象图,然后在c#中进行更多过滤(对对象的限制)。 这是通过使用ToList()
调用完成的。
public Client FindClientByMobile(string mobile, string accountId)
{
var clients = RepositorySet.Include("Account").Where(c => c.AccountId == accountId && !c.IsDeleted).ToList();
return clients.FirstOrDefault(client => Convert(client.TelephoneHome) == mobile || Convert(client.TelephoneMobile) == mobile || Convert(client.TelephoneWork) == mobile);
}
如您在评论中所述,这是否适合您
@Imad,我想做的是验证,因此,如果数字已以0331-9000-100的形式存储在数据库中,我想删除所有非数字字符,mobile已经应用了此功能,因此mobile = 033319000100
public Client FindClientByMobile(string mobile, string accountId)
{
Client client = RepositorySet.Include("Account").FirstOrDefault(c => c.AccountId == accountId && !c.IsDeleted
&& ((c.TelephoneHome.Replace("-","") == mobile) || (Convert(c.TelephoneMobile) == mobile) || (Convert(c.TelephoneWork) == mobile)));
return client;
}
使用“ Replace
您还可以替换其他字符,例如(
和)
。
需要记住的要点: Replace(char, char)
将不起作用,但是Replace(string, string)
将起作用。
第一个问题是Convert调用是C#,不能转换为SQL。 并非所有函数都可以,但是某些(例如子字符串)对于Entity Framework是“已知的”,它可以将它们转换为适当的SQL。 因此,您需要重写语句以使用EF知道的字符串函数,或者以其他方式将逻辑下推到数据库中。
@Imad已经建议使用string.Replace
,这是众所周知的EF,当然它不会帮你移除一切可能的非数字字符-只有那些你明确地编码,如“ - ”,而不是其他阿尔法像“扩展名”这样的字符串。
如果您想加快速度,最好将“清除的”数字存储在单独的字段中。 然后查询变为
Client client = RepositorySet.Include("Account").FirstOrDefault(c => c.AccountId == accountId && !c.IsDeleted
&& (c.TelephoneHomeClean == mobile) || (c.TelephoneMobileClean == mobile) || (c.TelephoneWorkClean == mobile)));
return client;
而且您可以更快地建立索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.