为什么LINQ to Entities不承认方法的系统。字符串ToString()?

[英]Why LINQ to Entities does not recognize the method 'System.String ToString()?


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

在MVC3 web应用程序中获取错误。LINQ to实体不识别方法的系统。字符串ToString()'方法,此方法不能转换为存储表达式。

when i try to fetch values using EF from query :

当我尝试从query获取值时:

public class DataRepository
    {
        public mydataEntities1 dbContext = new mydataEntities1();

        public List<SelectListItem> GetPricingSecurityID()
        {
        var pricingSecurityID = (from m in dbContext.Reporting_DailyNAV_Pricing
                                     select new SelectListItem
                                         {
                                                Text = m.PricingSecurityID.ToString(),
                                                Value = m.PricingSecurityID.ToString()
                                         });

        return pricingSecurityID.ToList();
        }
    }

7 个解决方案

#1


54  

That can't be converted to SQL. I guess, in theory, it could, but isn't implemented.

不能将其转换为SQL。我想,在理论上,它是可以实现的,但是没有实现。

You just need to perform your projection after you have your results:

你只需要在得到结果后执行你的投影:

var pricingSecurityID = (from m in dbContext.Reporting_DailyNAV_Pricing
                                     select m.PricingSecurityID).AsEnumerable()
    .Select(x => new SelectListItem{ Text = x.ToString(), Value = x.ToString() });

#2


17  

If it's already a string, why are you bothering to call ToString in the first place? I suspect a translation wasn't included in LINQ to Entities because it's pointless. Change your select clause to:

如果它已经是一个字符串,那么为什么一开始就麻烦地调用ToString呢?我怀疑LINQ中没有包含对实体的翻译,因为它毫无意义。将选择条款更改为:

select new SelectListItem
{
    Text = m.PricingSecurityID,
    Value = m.PricingSecurityID
}

If you really need to do something which isn't supported by LINQ to Entities, use AsEnumerable to transition from a database query to in-process:

如果您确实需要做一些LINQ不支持的事情到实体,请使用AsEnumerable来从数据库查询转换到进程内查询:

public List<SelectListItem> GetPricingSecurityID()
{
    return dbContext.Reporting_DailyNAV_Pricing
                    .Select(m => m.PricingSecurityID)
                    .AsEnumerable() // Rest of query is local
                    // Add calls to ToString() if you really need them...
                    .Select(id => new SelectListItem { Text = id, Value = id })
                    .ToList();
}

I agree with Jason's objections too, btw. You'd be better off returning a List<string> which is rendered elsewhere.

顺便说一句,我也同意杰森的反对意见。您最好返回一个列表 ,它在其他地方呈现。

Also note that if you're just going to use a single select clause or just a where clause, query expressions really don't add much - calling the LINQ extension methods can end up with less clutter, particularly if you want to call methods which aren't supported in query expressions (such as ToList).

还要注意,如果你只是要用单个select子句或只是一个where子句,查询表达式真的不增加太多——调用LINQ扩展方法可以用更少的混乱,尤其是如果你想调用方法不支持在查询表达式(比如ToList)。

#3


4  

Because it's trying to convert it to SQL, and it can't. Drop off the call to ToString, and do a projection before you return to the caller. So, replace your select clause with

因为它试图把它转换成SQL,但它不能。放下对ToString的调用,在返回给调用者之前做一个投影。因此,将select子句替换为

select m.PricingSecurityID

and then say

然后说

return pricingSecurityID
           .AsEnumerable()
           .Select(x => x.ToString())
           .Select(x => new SelectListItem { Text = x, Value = x })
           .ToList();

Also, I note that you're mixing UI concerns and data querying concerns. This is generally a bad practice. Really, you should just be returning the list of IDs and let the UI portion of your code worry about finagling it into the right form.

另外,我注意到您混合了UI关注点和数据查询关注点。这通常是个坏习惯。实际上,您应该返回id列表,并让代码的UI部分担心如何将其确定为正确的形式。

#4


4  

How about this. In this example, both the VDN field in the db and the Skill field are integers. I'm looking for matches from both fields so I have 2 compares.

这个怎么样。在本例中,db中的VDN字段和Skill字段都是整数。我在两个字段中寻找匹配所以我有两个比较。

Include this:

包括:

using System.Data.Objects.SqlClient; // needed to convert numbers to strings for linq

When comparing numbers do this:

当比较数字时,可以这样做:

        // Search Code
            if (!String.IsNullOrEmpty(searchString))
            {
                depts = depts.Where(d => SqlFunctions.StringConvert((double)d.VDN).Contains(searchString.ToUpper())
                || SqlFunctions.StringConvert((double)d.Skill).Contains(searchString.ToUpper()));
            }
        // End Search Code

Workie.

Workie。

#5


3  

Sadly EF does not know how to convert .ToString() You must use embedded function SqlFunctions.StringConvert: http://msdn.microsoft.com/en-us/library/dd466292.aspx Also there is no overload for int so you must typecast to double :-(

遗憾的是,EF不知道如何转换. tostring(),您必须使用嵌入式函数sqlfunction。StringConvert: http://msdn.microsoft.com/en-us/library/dd466292.aspx对于int也没有重载,所以必须将类型转换为double:-(

var vendors = 
   from v in Vendors  
   select new
   {             
       Code = SqlFunctions.StringConvert((double)v.VendorId)
   }; 

#6


1  

I understand that this question is answered and I agree that using AsEnumerable() is the way to go. However I would like to highlight a common scenario that I usually come across where AsEnumerable() is used inefficiently to resolve this error.

我知道这个问题得到了回答,我同意使用AsEnumerable()是一种方法。但是,我想强调一个我经常遇到的常见场景,即使用AsEnumerable()不能有效地解决这个错误。

From .NET Language-Integrated Query for Relational Data

来自。net语言集成的关系数据查询

The AsEnumerable() operator, unlike ToList() and ToArray(), does not cause execution of the query. It is still deferred. The AsEnumerable() operator merely changes the static typing of the query, turning a IQueryable into an IEnumerable, tricking the compiler into treating the rest of the query as locally executed.

与ToList()和ToArray()不同,AsEnumerable()操作符不会导致查询的执行。它仍然是递延。AsEnumerable()操作符仅仅改变查询的静态类型,将IQueryable转换为IEnumerable,使编译器将查询的其余部分视为本地执行。

References

引用

  1. Am I misunderstanding LINQ to SQL .AsEnumerable()?
  2. 我是否误解了LINQ到SQL .AsEnumerable()?
  3. Understanding .AsEnumerable() in LINQ to SQL
  4. 在LINQ to SQL中理解.AsEnumerable()。

Inefficient way

低效率的方式

IEnumerable<InvoiceDTO> inefficientEnumerable = 
     (from a in db.Invoices
     where a.Practice_Key == practiceKey.FirstOrDefault()
     select a
     ).AsEnumerable().
     Select(x => new InvoiceDTO
                             {
                                 InvoiceID = x.InvoiceID,
                                 PracticeShortName = x.Dim_Practice.Short_Name,
                                 InvoiceDate = x.InvoiceDate,
                                 InvoiceTotal = x.InvoiceAmount,
                                 IsApproved = x.IsApproved,
                                 InvoiceStatus = (
                                                  x.IsApproved == null ? "Pending" :
                                                  x.IsApproved == true ? "Approved" :
                                                  x.IsApproved == false ? "Rejected" : "Unknown"
                                                ),
                                 InvoicePeriodStartDateText = x.InvoicePeriodStart.ToShortDateString(),
                                 InvoicePeriodEndDateText = x.InvoicePeriodEnd.ToShortDateString(),
                                 InvoicePeriodStartDate = x.InvoicePeriodStart,
                                 InvoicePeriodEndDate = x.InvoicePeriodEnd
                             }
                             );

            invoices = inefficientEnumerable.ToList();

Here the AsEnumerable is used for the entire table. All the columns are getting selected eventhough they are not needed.

这里,AsEnumerable用于整个表。即使不需要,也会选择所有列。

Better Way

更好的方法

 IQueryable<InvoiceDTO> invoicesQuery = 
   (from a in db.Invoices
   where a.Practice_Key == practiceKey.FirstOrDefault()
   select new InvoiceDTO
            {
             InvoiceID = a.InvoiceID,
             PracticeShortName = a.Dim_Practice.Short_Name,
             InvoiceDate = a.InvoiceDate,
             InvoiceTotal = a.InvoiceAmount,
             IsApproved = a.IsApproved,
             InvoiceStatus = (
                               a.IsApproved == null ? "Pending" :
                               a.IsApproved == true ? "Approved" :
                               a.IsApproved == false ? "Rejected" :"Unknown"
                               ),
             InvoicePeriodStartDate = a.InvoicePeriodStart,
             InvoicePeriodEndDate = a.InvoicePeriodEnd
          });


          IEnumerable<InvoiceDTO> betterEnumerable = invoicesQuery.AsEnumerable().
          Select(x => new InvoiceDTO
                                 {
                                     InvoiceID = x.InvoiceID,
                                     PracticeShortName = x.PracticeShortName,
                                     InvoiceDate = x.InvoiceDate,
                                     InvoiceTotal = x.InvoiceTotal,
                                     IsApproved = x.IsApproved,
                                     InvoiceStatus = x.InvoiceStatus,
                                     InvoicePeriodStartDateText = x.InvoicePeriodStartDate.ToShortDateString(),
                                     InvoicePeriodEndDateText = x.InvoicePeriodEndDate.ToShortDateString(),
                                     InvoicePeriodStartDate = x.InvoicePeriodStartDate,
                                     InvoicePeriodEndDate = x.InvoicePeriodEndDate
                                 }
                                 );

#7


-3  

return dbContext.Reporting_DailyNAV_Pricing.AsEnumerable().Select(x => new SelectListItem
{
    Text = x.PricingSecurityID.ToString(),
    Value = x.PricingSecurityID.ToString()
}).ToList();
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2012/04/11/7202dff39badc46c086cdc4d34c16676.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告