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

后端 未结 11 2040
花落未央
花落未央 2020-11-22 10:41

I\'m migrating some stuff from one mysql server to a sql server but i can\'t figure out how to make this code work:

using (var context = new Context())
{
            


        
11条回答
  •  囚心锁ツ
    2020-11-22 11:17

    If you really want to type ToString inside your query, you could write an expression tree visitor that rewrites the call to ToString with a call to the appropriate StringConvert function:

    using System.Linq;
    using System.Data.Entity.SqlServer;
    using System.Linq.Expressions;
    using static System.Linq.Expressions.Expression;
    using System;
    
    namespace ToStringRewriting {
        class ToStringRewriter : ExpressionVisitor {
            static MethodInfo stringConvertMethodInfo = typeof(SqlFunctions).GetMethods()
                     .Single(x => x.Name == "StringConvert" && x.GetParameters()[0].ParameterType == typeof(decimal?));
    
            protected override Expression VisitMethodCall(MethodCallExpression node) {
                var method = node.Method;
                if (method.Name=="ToString") {
                    if (node.Object.GetType() == typeof(string)) { return node.Object; }
                    node = Call(stringConvertMethodInfo, Convert(node.Object, typeof(decimal?));
                }
                return base.VisitMethodCall(node);
            }
        }
        class Person {
            string Name { get; set; }
            long SocialSecurityNumber { get; set; }
        }
        class Program {
            void Main() {
                Expression> expr = x => x.ToString().Length > 1;
                var rewriter = new ToStringRewriter();
                var finalExpression = rewriter.Visit(expr);
                var dcx = new MyDataContext();
                var query = dcx.Persons.Where(finalExpression);
    
            }
        }
    }
    

提交回复
热议问题