C # conversion between Dto Linq Expression and Model Linq Expression in the database in ORM,

Source: Internet
Author: User

C # conversion between Dto Linq Expression and Model Linq Expression in the database in ORM,

Today, I saw a question in Baidu zhixing. After studying it for a while, I answered:

Http://zhidao.baidu.com/question/920461189016484459.html

How to convert a dto linq expression to a database object linq expression. It is feasible to collect some information and practice it.

One method of self-ScalingCast<TInput, TToProperty>(this Expression<Func<TInput, bool> Expression), the Code is as follows:

Namespace System {public static class LambdaExpressionExtensions {private static Expression Parser (ParameterExpression parameter, Expression expression) {if (expression = null) return null; switch (expression. nodeType) {// The unary operator case ExpressionType. negate: case ExpressionType. netricchecked: case ExpressionType. not: case ExpressionType. convert: case ExpressionType. convertChecked: case ExpressionT Ype. arrayLength: case ExpressionType. quote: case ExpressionType. typeAs: {var unary = expression as UnaryExpression; var exp = Parser (parameter, unary. operand); return Expression. makeUnary (expression. nodeType, exp, unary. type, unary. method);} // binary operator case ExpressionType. add: case ExpressionType. addChecked: case ExpressionType. subtract: case ExpressionType. subtractChecked: case ExpressionType. mult Iply: case ExpressionType. multiplyChecked: case ExpressionType. divide: case ExpressionType. modulo: case ExpressionType. and: case ExpressionType. andAlso: case ExpressionType. or: case ExpressionType. orElse: case ExpressionType. lessThan: case ExpressionType. lessThanOrEqual: case ExpressionType. greaterThan: case ExpressionType. greaterThanOrEqual: case ExpressionType. equal: case ExpressionType. notEqual: Case ExpressionType. coalesce: case ExpressionType. arrayIndex: case ExpressionType. rightShift: case ExpressionType. leftShift: case ExpressionType. exclusiveOr: {var binary = expression as BinaryExpression; var left = Parser (parameter, binary. left); var right = Parser (parameter, binary. right); var conversion = Parser (parameter, binary. conversion); if (binary. nodeType = ExpressionType. coalesce && Binary. Conversion! = Null) {return Expression. coalesce (left, right, conversion as LambdaExpression);} else {return Expression. makeBinary (expression. nodeType, left, right, binary. isLiftedToNull, binary. method) ;}}// other case ExpressionType. call: {var call = expression as MethodCallExpression; List <Expression> arguments = new List <Expression> (); foreach (var argument in call. arguments) {arguments. add (Parser (parameter, argument);} var instance = Parser (parameter, call. object); call = Expression. call (instance, call. method, arguments); return call;} case ExpressionType. lambda: {var Lambda = expression as LambdaExpression; return Parser (parameter, Lambda. body);} case ExpressionType. memberAccess: {var memberAccess = expression as MemberExpression; if (memberAccess. expression = null) {memberAccess = Expression. makeMemberAccess (null, memberAccess. member);} else {var exp = Parser (parameter, memberAccess. expression); var member = exp. type. getMember (memberAccess. member. name ). firstOrDefault (); memberAccess = Expression. makeMemberAccess (exp, member);} return memberAccess;} case ExpressionType. parameter: return parameter; case ExpressionType. constant: return expression; case ExpressionType. typeIs: {var typeis = expression as TypeBinaryExpression; var exp = Parser (parameter, typeis. expression); return Expression. typeIs (exp, typeis. typeOperand);} default: throw new Exception (string. format ("Unhandled expression type: '{0}'", expression. nodeType);} public static Expression <Func <TToProperty, bool> Cast <TInput, TToProperty> (this Expression <Func <TInput, bool> expression) {var p = Expression. parameter (typeof (TToProperty), "p"); var x = Parser (p, expression); return Expression. lambda <Func <TToProperty, bool> (x, p );}}}

For example, there are the following object class objects:

    public class User    {        public int Id { get; set; }        public string Name { get; set; }    }    public class UserDto    {        public int Id { get; set; }        public string Name { get; set; }    }

Simple test code:

Class Program {static int [] array0 = new [] {0, 1}; static void Main1 (string [] args) {var array1 = new [] {0, 1 }; expression <Func <UserDto, bool> exp = null; Expression <Func <User, bool> exp2 = null; // ===== exp ====/// exp = u => u. name = "zhangsan"; // exp = u => u. id. equals (1); // exp = u => u. id. equals (1) & u. name = "zhangsan"; // exp = u => u. id. equals (1) & u. name = "James" | u. name = "zhangsan"; // exp = u => Filter (u. Name); // exp = u =>! Filter (u. name); // exp = u => u. id. equals (1) & u. name = "Zhang San" & Filter (u. name); // exp = u => array1.Contains (u. id); // exp = u => array1.Contains (u. id) | u. name = "zhangsan"; // exp = u => array0.Contains (u. id); // exp = u => u. id> 0; // exp = u => u. id <10; // exp = u => u. id * 2 <10; // exp = u => u. id-2 <10; // exp = u => u. id + 2 <10; // exp = u => u. id/2 <10; // exp = u => (int) (u. id/2) <10; // exp = u => u. name is string; // exp = u => (object) u. id ). toString () = "1"; // exp = u => u. id = default (int); // exp = u => true; // exp = u => Math. abs (u. id) = 1; exp = u => u. id. equals (1) & u. name = "Zhang San" & u. id <10 & array1.Contains (u. id) & u. id + 2 <10 & (object) u. id ). toString () = "1" | u. name. contains ("3") & Math. abs (u. id) = 1 & Filter (u. name) & true; // ==== exp2 ==== exp2 = exp. cast <UserDto, User> (); Console. writeLine (exp. toString (); Console. writeLine (exp. toString (); // test data List <User> list = new List <User> () {new User {Id = 0, Name = "AAA "}, new User {Id = 1, Name = "Zhang San"}, new User {Id = 2, Name = "Li Si" }}; var item = list. where (exp2.Compile ()). firstOrDefault (); Console. writeLine (item. name); Console. readKey ();} public static bool Filter (string name) {return name. contains ("3 ");}}

It should be said that common filtering conditions are supported. The list here is simulated using List <User> because there is no database environment. You can change the real ORM environment to list. Where (exp2.

The performance is not tested and the cache can be used. If you are interested, you can change it.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.