Search for existing suggestions

Support ToString method in LINQ to Entities

Contrived example: LINQ to SQL supports a query like this:

from e in context.Customers
where e.Id.ToString() == "1"
select e;

The translation is:
SELECT [t0].[Id], [t0].[Name], [t0].[Points]FROM [dbo].[Customers] AS [t0]WHERE (CONVERT(NVarChar,[t0].[Id])) = @p0

LINQ to Entities does not support this yet, although it is possible to use CAST for similar purposes in Entity SQL.

35 votes
Sign in
Sign in with: Facebook Google
Signed in as (Sign out)

We’ll send you updates on this idea

AdminDiego Vega (Program Manager, Microsoft Entity Framework) shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →


Sign in
Sign in with: Facebook Google
Signed in as (Sign out)
  • Levi Page commented  ·   ·  Flag as inappropriate

    This works fine when you invoke in directly:
    var test2 = students.Where(x => x.FirstName.ToString().Contains("L"));
    But, not when you invoke it through reflection:
    Type dbType = typeof(Student);

    var dbFieldMemberInfo = dbType.GetMember("FirstName",
    BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance).Single();
    // Create an "x" as TDbType
    var dbTypeParameter = Expression.Parameter(dbType, @"x");
    // Get at x.firstName
    var dbFieldMember = Expression.MakeMemberAccess(dbTypeParameter, dbFieldMemberInfo);

    // Create the criterion as a constant
    var criterionConstant = new Expression[] { Expression.Constant(searchString) };
    var toStringMethod = typeof(Convert).GetMethod("ToString", Type.EmptyTypes);
    var toStringCall = Expression.Call(dbFieldMember, toStringMethod);
    var fancyContain = Expression.Call(toStringCall, StringContainsMethod, criterionConstant);
    var lambda = Expression.Lambda(fancyContain, dbTypeParameter) as Expression<Func<Student, bool>>;

    It produces the same lambda x.FirstName.ToString().Contains("") , but you get the old error that ToString can't be called

  • Matt commented  ·   ·  Flag as inappropriate

    Linq2Sql has it, why shouldn't Linq2EF be able to translate .ToString() into SQL properly? I came across this need a couple of is terribly uncomfortable having to use workarounds for it and creates ugly code and harder maintainable code too!

Feedback and Knowledge Base