Why does LINQ to Entities ignore the System.String ToString() method?

asp.net-mvc entity-framework linq

Question

Error occurring during 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.

while attempting to get values using EF from:

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();
        }
    }
1
30
4/11/2012 4:42:06 PM

Accepted Answer

This cannot be transformed into SQL. Theoretically, I suppose, it might, but it's not used.

Once you get your findings, you merely need to execute your projection:

var pricingSecurityID = (from m in dbContext.Reporting_DailyNAV_Pricing
                                     select m.PricingSecurityID).AsEnumerable()
    .Select(x => new SelectListItem{ Text = x.ToString(), Value = x.ToString() });
54
4/11/2012 8:37:38 PM

Popular Answer

Why are you calling if it's already a string?ToString at all, really? A translation, in my opinion, was left out of LINQ to Entities since it would be useless. Your pick clause should now read:

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

If you need to accomplish something that LINQ to Entities doesn't allow, useAsEnumerable converting a database query into an in-process:

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();
}

Besides, I agree with Jason's criticisms. It would be best for you to return aList<string> It is produced somewhere else.

Additionally, keep in mind that if you're only planning to employ oneselect sentence or simply awhere query expressions actually don't contribute that much, and invoking LINQ extension methods may result in less clutter, especially if you wish to use methods that query expressions didn't allow (suchToList ).



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow