C# 使用Linq问题

删除数据时候报错,提示信息:"LINQ to Entities does not recognize the method 'Int32 ToInt(System.Object)' method, and this method cannot be translated into a store expression."

        public void DeleteForm(string keyValue)
        {
            userService.Delete(t => t.Id == keyValue.ToInt());
        }

代码如上,问题出在lamada表达式上,修改如下:

        public void DeleteForm(string keyValue)
        {
            int num = keyValue.ToInt();
            var expression = ExtLinq.True<UserEntity>();
            expression = expression.And(t => t.Id == num);
            userService.Delete(expression);
        }

原理:

两部分代码,在debug的时候能看到expression的拼装:

{param => (True AndAlso (param.Id == value(Bond.Application.ApplyManage.UserApp+<>c__DisplayClass4).keyValue.ToInt()))}

{param => (True AndAlso (Convert(param.Id) == value(Bond.Application.ApplyManage.UserApp+<>c__DisplayClass4).num))}

结合网上找的解释,个人理解为:

Linq在解析的时候,不支持这种ToInt的转换,Linq有内置的函数,可以顺利的解析为对应的sql语句,而自定义的或者不支持的转换方式,需要将转换结果传入linq,作为静态比较值。

参考:https://stackoverflow.com/questions/10794754/sql-function-in-lambda-expression-in-ef-cannot-be-translated-into-a-store-expre 

 https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/bb738681(v=vs.100)?redirectedfrom=MSDN

 

posted @ 2020-01-14 11:23  normalpers  阅读(626)  评论(0编辑  收藏  举报