2012-03-02 67 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#。