簡體   English   中英

實體框架-字符串轉換錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM