2012-03-02 71 views
6

考慮下面的代碼如何格式化linq表達式中的字符串?

IQueryable<string> customers = 
    from Customers in db.Customers 
    where Customers.CstCompanyName.Contains(prefixText) && Customers.CstInactive == false 
    select Customers.CstCompanyName + " (Phone: " + Convert.ToInt64(Customers.CstPhone).ToString("###-###-#### ####") + ")"; 

這是我的實體框架的呼叫。我正在從數據庫中返回一個電話號碼。我試圖格式化給定的格式字符串。不幸的是,當我運行它,我收到以下錯誤:

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

所以我的問題是怎麼做的我回到這個數據庫對象爲格式的字符串?

謝謝!

+0

你需要結果是'IQueryable'嗎?難道你不能通過'var customers = ...'獲得一個'IEnumerable '? – 2012-03-02 14:47:38

+0

不要。讓數據庫處理數據;有演示文稿代碼處理。 – AakashM 2012-03-02 14:48:00

+0

最後,它以字符串[]的形式返回,所以無論什麼都可以實現。我目前正在做的是string [] cst = customers.ToArray();所以我不太確定它是否需要IQueryable。 – Kevin 2012-03-02 15:04:58

回答

21

我將履行在數據庫中查詢,但格式化本地:

var customers = db.Customers 
        .Where(c => c.CstCompanyName.Contains(prefixText)) 
        .Select(c => new { c.CstCompanyName, c.CstPhone }) 
        .AsEnumerable() // Switch to in-process 
        .Select(c => c.CstCompanyName + 
           " (Phone: " +    
           Convert.ToInt64(Customers.CstPhone) 
             .ToString("###-###-#### ####") + ")"); 
0

我不知道這是否是正確的方法,但我想用我的東西」很舒服。如果您使用實體框架並加載它,則可以將String.Format放置在LINQ查詢中。

Dim ds as Entity = New Entity() 
    ds.FinancialInstitutionTransactions.OrderByDescending(Function(c) c.TransID).Load() 

    Dim openLoad = From tr In ds.FinancialInstitutionTransactions.Local 
        Select TransDate = String.Format("{0:d}", tr.Date), 
        tr.Number, 
        tr.ToFrom, 
        Debit = If(tr.Debit = 0, " ".ToString(), String.Format("{0:N}", tr.Debit).ToString()), 
        Credit = If(tr.Credit = 0, " ".ToString(), String.Format("{0:N}", tr.Credit).ToString()) 

您需要引用System.Data.Entity的加載,但隨後就容易格式化的結果,你想要的任何方式。

我希望這會幫助別人。 我知道這是在VB.NET,但它不會很難轉換爲C#。