• 如何搭建.NET Entity Framework分布式应用系统框架


    一、             前言 

    ADO.NET Entity Framework(以下简称EF)是微软推出的一套O/RM框架,如果用过Linq To SQL的人会比较容易理解,因为Linq To SQL是微软在.net FrameWork 3.0时推出的一套轻量级的O/RM框架,但是只支持SQL Server一种数据库。至.net FrameWork 3.5 sp1时,才推出Entity FrameWork,可以通过实现不同的Provider来支持不同的数据库(当然微软还是只内置SQL ServerProvider,其它数据库的Provider么,需要第三方开发)。EF加上linq,这是.net开发上的一个巨大进步,.net程序员以对象方式操作数据,以类sql语法在程序里查询数据,大大减少了繁琐的构造SQL语句的工作,可以更加专注于编写业务逻辑代码。但是在多层架构的分布式应用系统中,实体对象通过远程序列化到客户端时,这些实体会与其数据上下文(也就是实体容器)分离,在客户端无法对实体直接进行查询以及CUDCreate,Update,Delete操作,下面以SQL Server为数据库,Remoting+Entity Framework3.5作为数据服务层,WinForm作为客户端,讲述一下如何使用EF框架搭建多层分布式应用系统。

     

    二、             技术分析 

    1.   通过远程客户端传输过来的实体,都是处于分离状态(EntityState属性值为Detached),所以在多层应用程序中的服务端实现实体的更新或删除时,关键是如何把实体附加回实体容器中。MSDN上关于对分离实体的查询和CUD操作描述如下: 

    1)     附加对象(实体框架) 

    在实体框架的某个对象上下文内执行查询时,返回的对象会自动附加到该对象上下文。还可以将从源而不是从查询获得的对象附加到对象上下文。您可以附加以前分离的对象、由 NoTracking 查询返回的对象或从对象上下文的外部获取的对象。还可以附加存储在 ASP.NET 应用程序的视图状态中的对象或从远程方法调用或 Web 服务返回的对象。 

    使用下列方法之一将对象附加到对象上下文: 

    ·         调用 ObjectContext 上的 AddObject 将对象附加到对象上下文。当对象为数据源中尚不存在的新对象时采用此方法。 

    ·         调用 ObjectContext上的 Attach 将对象附加到对象上下文。当对象已存在于数据源中但当前尚未附加到上下文时采用此方法。有关更多信息,请参见如何:附加相关对象(实体框架)。 

    ·         调用 ObjectContext AttachTo,以将对象附加到对象上下文中的特定实体集。如果对象具有 null(在 Visual Basic 中为 NothingEntityKey 值,也可以执行此操作。 

    ·         调用 ObjectContext上的 ApplyPropertyChanges。当对象已存在于数据源中,并且分离的对象具有您希望保存的属性更新时采用此方法。如果简单地附加该对象,则属性更改将丢失。有关更多信息,请参见如何:应用对已分离对象的更改(实体框架)。 

    2)        应用对已分离对象的更改(实体框架)示例代码  

                     

    View Code
    privatestaticvoid ApplyItemUpdates(SalesOrderDetail updatedItem)
    {
    // Define an ObjectStateEntry and EntityKey for the current object.
    EntityKey key;
    object originalItem;
    using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
    {
    try
    {
    // Create the detached object's entity key.
    key = advWorksContext.CreateEntityKey("SalesOrderDetail", updatedItem);

    // Get the original item based on the entity key from the context
    // or from the database.
    if (advWorksContext.TryGetObjectByKey(key, out originalItem))
    {
    // Call the ApplyPropertyChanges method to apply changes
    // from the updated item to the original version.
    advWorksContext.ApplyPropertyChanges(
    key.EntitySetName, updatedItem);
    }

    advWorksContext.SaveChanges();
    }
    catch (InvalidOperationException ex)
    {
    Console.WriteLine(ex.ToString());
    }
    }
    }

    2.         实现动态条件查询。在本地环境中,对于Linq,我们可以通过动态构造Lambda表达式树来实现动态条件查询,但是在远程环境中,Lamdba表达式不支持远程序列化传输,只能通过ObjectContextCreateQuery方法实现,但幸好微软后来又提供了一个LINQ动态查询扩展库Dynamic.cs,使用起来更方便,于是采用它实现。

     

    3.         EF中核心抽象类是ObjectContext,实体容器都从它派生,实体容器上的CUD方法其实都是通过调用ObjectContextCUD操作方法实现的。

    1)        AddObject(string,object):表示添加实体object到实体容器,只要实体的EntityKey值为空,无论是否Detached状态均可以通过此方法实现添加操作。

    2)        ApplyPropertyChanges(string,object)表示把分离状态的实体object上的所作的修改更新回容器中已存在的对应的实体,执行条件有两个:实体处于分离状态,实体容器中存在主键值与其相同的且为Unchanged状态的实体,所以,当我们需要更新一个Detached状态的实体时,可以先把一个具有原始值的相同键值的实体附加回容器中,或者直接执行一下查询,从数据库中取出该实体。

    3)        DeleteObject(object)表示从实体容器中删除一个实体,执行条件是该实体存在于实体容器中,所以删除一个Detach状态的实体之前,需要把它通过Attach方法附加回实体容器中。

     

    4.         实体对象也是基于抽象类EntityObject派生的,由此我们完全可以用ContextObjectEntityObject实现服务端对实体的查询和CUD方法,其实现子类在运行时由客户端注入,从而使服务端和数据库实现松耦合。

     

    5.         下图是MSDN上关于在数据访问层中使用 LINQ to SQL n 层应用程序的基本体系结构图,其实EF的结构也是一样的,不过是把DataContext换成ObjectContext 

     

     

     

    三、             动手开发 

    1.         利用EF建立数据库概念模型

    新建一个解决方案EFServiceSystem,添加一个新项目,命名为EFModel,添加项目,在项目下添加一个ADO.NET Entity Data Model项,命名为EFModel.edmx,选择从数据库生成(假设我们已经建好了一个SQL Server数据库),一路点击下一步,直至完成。编译项目成功后就算完成。为什么要把数据库模型单独编译成一个dll呢,我将在后面给予解释。

     

     

    2.         建立数据服务层

    在解决方案下再添加一个类库项目,命名为EFService

    1)        利用外观模式,我们把客户端常用的查询和CUD操作方法简化为3个方法Query<T>,Save(T t),Delete(T t),根据针对接口编程的设计原则,定义一个CUD方法接口供客户端调用。

     

    View Code
    using System;

    using System.Collections.Generic;

    using System.Text;

    namespace EFService

    {

    publicinterface IEntityHelper

    {

    List
    <T> Query<T>(string filter,paramsobject[] args);

    T Save
    <T>(T t);

    int Delete<T>(T t);

    }

    }

     

    2)        实现类EntityHelper的代码。主要思路是通过构造函数注入数据上下文实例名称,在配置文件取出其程序集限定名,通过反射创建实例,调用实例的相应方法实现接口。

     

    View Code
    using System;

    using System.Collections.Generic;

    using System.Text;

    using System.Data.Objects;

    using System.Data.Objects.DataClasses;

    using System.Reflection;

    using System.Linq;

    using System.Linq.Dynamic;

    using System.Runtime.Remoting;



    namespace EFService

    {

    ///<summary>

    /// 为远程客户端提供实体查询和CUD操作的服务类

    ///</summary>

    publicclass EntityHelper : MarshalByRefObject, IEntityHelper

    {

    ///<summary>

    /// 在config文件中配置的数据上下文名称

    ///</summary>

    string ContextName;

    ServiceFactory factory
    =new ServiceFactory();

    public EntityHelper(string contextName)

    {

    ContextName
    = contextName;

    }



    ///<summary>

    /// 创建数据上下文实例

    ///</summary>

    ///<returns></returns>

    public ObjectContext CreateObjectContext()

    {

    string typeName = System.Configuration.ConfigurationManager.AppSettings[ContextName].ToString();

    return (ObjectContext)Activator.CreateInstance(Type.GetType(typeName));

    }



    ///<summary>

    /// 查询操作

    ///</summary>

    ///<typeparam name="T"></typeparam>

    ///<param name="filter">查询条件组合</param>

    ///<param name="args">查询条件中的参数值</param>

    ///<returns>返回实体集合</returns>

    public List<T> Query<T>(string filter, paramsobject[] args)

    {

    using (ObjectContext context = CreateObjectContext())

    {

    return (context.GetType().InvokeMember(

    typeof(T).Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, null, context, null)

    as IQueryable<T>).Where(filter, args).ToList();

    }

    }



    ///<summary>

    /// 保存实体

    ///</summary>

    ///<typeparam name="T"></typeparam>

    ///<param name="t">要添加或修改的实体</param>

    ///<returns>返回添加或者更新后的实体</returns>

    public T Save<T>(T t)

    {

    EntityObject eo
    = t as EntityObject;

    using (ObjectContext context = CreateObjectContext())

    {

    if (eo.EntityKey ==null)

    {

    context.AddObject(t.GetType().Name, t);

    }

    else

    {

    object target = ontext.GetObjectByKey(eo.EntityKey); context.ApplyPropertyChanges(eo.EntityKey.EntitySetName, eo);

    }

    context.SaveChanges();

    return t;

    }

    }



    ///<summary>

    /// 删除实体

    ///</summary>

    ///<typeparam name="T"></typeparam>

    ///<param name="t"></param>

    ///<returns>成功删除的实体的数量</returns>

    publicint Delete<T>(T t)

    {

    EntityObject eo
    = t as EntityObject;

    using (ObjectContext context = CreateObjectContext())

    {

    if (eo !=null&& eo.EntityKey !=null)

    context.Attach(eo);

    context.DeleteObject(eo);

    return context.SaveChanges();

    }

    }

    }

    }

     

    3)        最后,我们创建一个服务工厂类,暴露给客户端,负责以接口方式向客户端提供远程服务对象,数据服务层创建完毕 

     

     

    View Code
    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Data.Objects;

    using System.Configuration;



    namespace EFService

    {

    ///<summary>

    /// 远程服务类工厂,负责创建服务对象

    ///</summary>

    publicclass ServiceFactory : MarshalByRefObject

    {

    ///<summary>

    /// 创建远程服务对象

    ///</summary>

    ///<param name="connStringName">数据上下文名称</param>

    ///<returns>远程服务接口</returns>

    public IEntityHelper CreateEntityHelper(string contextName)

    {

    returnnew EntityHelper(contextName);

    }

    }

    }

     

    4)  补充一下Dynamic.cs的内容,省得你去网上找了

    View Code
    //Copyright (C) Microsoft Corporation.  All rights reserved.
    
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;
    using System.Reflection.Emit;
    using System.Threading;
    using System.Data.Objects;
    
    namespace System.Linq.Dynamic
    {
        [Serializable]
        public static class DynamicQueryable
        {
            /*************************/
    
    
            public static IQueryable<TSource> WhereLike<TSource>(
               this IQueryable<TSource> source,
               Expression<Func<TSource, string>> valueSelector,
               string value,
               char wildcard)
            {
                return source.Where(BuildLikeExpression(valueSelector, value, wildcard));
            }
    
            public static Expression<Func<TElement, bool>> BuildLikeExpression<TElement>(
                Expression<Func<TElement, string>> valueSelector,
                string value,
                char wildcard)
            {
                if (valueSelector == null)
                    throw new ArgumentNullException("valueSelector");
    
                var method = GetLikeMethod(value, wildcard);
    
                value = value.Trim(wildcard);
                var body = Expression.Call(valueSelector.Body, method, Expression.Constant(value));
    
                var parameter = valueSelector.Parameters.Single();
                return Expression.Lambda<Func<TElement, bool>>(body, parameter);
            }
    
            private static MethodInfo GetLikeMethod(string value, char wildcard)
            {
                var methodName = "Contains";
    
                var textLength = value.Length;
                value = value.TrimEnd(wildcard);
                if (textLength > value.Length)
                {
                    methodName = "StartsWith";
                    textLength = value.Length;
                }
    
                value = value.TrimStart(wildcard);
                if (textLength > value.Length)
                {
                    methodName = (methodName == "StartsWith") ? "Contains" : "EndsWith";
                    textLength = value.Length;
                }
    
                var stringType = typeof(string);
                return stringType.GetMethod(methodName, new Type[] { stringType });
            }
    
    
            /********************************/
    
    
            public static string ToTraceString(this IQueryable query)
            {
                System.Reflection.MethodInfo toTraceString = query.GetType().GetMethod("ToTraceString");
                if (toTraceString != null)
                    return toTraceString.Invoke(query,null).ToString();
                return string.Empty;
                
            }
    
            public static IQueryable<TEntity> WhereIn<TEntity, TValue>
         (
             this IQueryable<TEntity> query,
             Expression<Func<TEntity, TValue>> selector,
             IEnumerable<TValue> collection
         )
            {
                if (selector == null) throw new ArgumentNullException("selector");
                if (collection == null) throw new ArgumentNullException("collection");
                ParameterExpression p = selector.Parameters.Single();
    
                if (!collection.Any()) return query;
    
                IEnumerable<Expression> equals = collection.Select(value =>
                   (Expression)Expression.Equal(selector.Body,
                        Expression.Constant(value, typeof(TValue))));
    
                Expression body = equals.Aggregate((accumulate, equal) =>
                    Expression.Or(accumulate, equal));
    
                return query.Where(Expression.Lambda<Func<TEntity, bool>>(body, p));
            }
    
    
            public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values)
            {
                return (IQueryable<T>)Where((IQueryable)source, predicate, values);
            }
    
            public static IQueryable Where(this IQueryable source, string predicate, params object[] values)
            {
                if (source == null) throw new ArgumentNullException("source");
                if (predicate == null) throw new ArgumentNullException("predicate");
                LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values);
                return source.Provider.CreateQuery(
                    Expression.Call(
                        typeof(Queryable), "Where",
                        new Type[] { source.ElementType },
                        source.Expression, Expression.Quote(lambda)));
            }
    
            public static IQueryable Select(this IQueryable source, string selector, params object[] values)
            {
                if (source == null) throw new ArgumentNullException("source");
                if (selector == null) throw new ArgumentNullException("selector");
                LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, null, selector, values);
                return source.Provider.CreateQuery(
                    Expression.Call(
                        typeof(Queryable), "Select",
                        new Type[] { source.ElementType, lambda.Body.Type },
                        source.Expression, Expression.Quote(lambda)));
            }
    
            public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values)
            {
                return (IQueryable<T>)OrderBy((IQueryable)source, ordering, values);
            }
    
            public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values)
            {
                if (source == null) throw new ArgumentNullException("source");
                if (ordering == null) throw new ArgumentNullException("ordering");
                ParameterExpression[] parameters = new ParameterExpression[] {
                    Expression.Parameter(source.ElementType, "") };
                ExpressionParser parser = new ExpressionParser(parameters, ordering, values);
                IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();
                Expression queryExpr = source.Expression;
                string methodAsc = "OrderBy";
                string methodDesc = "OrderByDescending";
                foreach (DynamicOrdering o in orderings)
                {
                    queryExpr = Expression.Call(
                        typeof(Queryable), o.Ascending ? methodAsc : methodDesc,
                        new Type[] { source.ElementType, o.Selector.Type },
                        queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters)));
                    methodAsc = "ThenBy";
                    methodDesc = "ThenByDescending";
                }
                return source.Provider.CreateQuery(queryExpr);
            }
    
            public static IQueryable Take(this IQueryable source, int count)
            {
                if (source == null) throw new ArgumentNullException("source");
                return source.Provider.CreateQuery(
                    Expression.Call(
                        typeof(Queryable), "Take",
                        new Type[] { source.ElementType },
                        source.Expression, Expression.Constant(count)));
            }
    
            public static IQueryable Skip(this IQueryable source, int count)
            {
                if (source == null) throw new ArgumentNullException("source");
                return source.Provider.CreateQuery(
                    Expression.Call(
                        typeof(Queryable), "Skip",
                        new Type[] { source.ElementType },
                        source.Expression, Expression.Constant(count)));
            }
    
            public static IQueryable GroupBy(this IQueryable source, string keySelector, string elementSelector, params object[] values)
            {
                if (source == null) throw new ArgumentNullException("source");
                if (keySelector == null) throw new ArgumentNullException("keySelector");
                if (elementSelector == null) throw new ArgumentNullException("elementSelector");
                LambdaExpression keyLambda = DynamicExpression.ParseLambda(source.ElementType, null, keySelector, values);
                LambdaExpression elementLambda = DynamicExpression.ParseLambda(source.ElementType, null, elementSelector, values);
                return source.Provider.CreateQuery(
                    Expression.Call(
                        typeof(Queryable), "GroupBy",
                        new Type[] { source.ElementType, keyLambda.Body.Type, elementLambda.Body.Type },
                        source.Expression, Expression.Quote(keyLambda), Expression.Quote(elementLambda)));
            }
    
            public static bool Any(this IQueryable source)
            {
                if (source == null) throw new ArgumentNullException("source");
                return (bool)source.Provider.Execute(
                    Expression.Call(
                        typeof(Queryable), "Any",
                        new Type[] { source.ElementType }, source.Expression));
            }
    
            public static int Count(this IQueryable source)
            {
                if (source == null) throw new ArgumentNullException("source");
                return (int)source.Provider.Execute(
                    Expression.Call(
                        typeof(Queryable), "Count",
                        new Type[] { source.ElementType }, source.Expression));
            }
        }
    
        public abstract class DynamicClass
        {
            public override string ToString()
            {
                PropertyInfo[] props = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                StringBuilder sb = new StringBuilder();
                sb.Append("{");
                for (int i = 0; i < props.Length; i++)
                {
                    if (i > 0) sb.Append(", ");
                    sb.Append(props[i].Name);
                    sb.Append("=");
                    sb.Append(props[i].GetValue(this, null));
                }
                sb.Append("}");
                return sb.ToString();
            }
        }
    
        public class DynamicProperty
        {
            string name;
            Type type;
    
            public DynamicProperty(string name, Type type)
            {
                if (name == null) throw new ArgumentNullException("name");
                if (type == null) throw new ArgumentNullException("type");
                this.name = name;
                this.type = type;
            }
    
            public string Name
            {
                get { return name; }
            }
    
            public Type Type
            {
                get { return type; }
            }
        }
    
        public static class DynamicExpression
        {
            public static Expression Parse(Type resultType, string expression, params object[] values)
            {
                ExpressionParser parser = new ExpressionParser(null, expression, values);
                return parser.Parse(resultType);
            }
    
            public static LambdaExpression ParseLambda(Type itType, Type resultType, string expression, params object[] values)
            {
                return ParseLambda(new ParameterExpression[] { Expression.Parameter(itType, "") }, resultType, expression, values);
            }
    
            public static LambdaExpression ParseLambda(ParameterExpression[] parameters, Type resultType, string expression, params object[] values)
            {
                ExpressionParser parser = new ExpressionParser(parameters, expression, values);
                return Expression.Lambda(parser.Parse(resultType), parameters);
            }
    
            public static Expression<Func<T, S>> ParseLambda<T, S>(string expression, params object[] values)
            {
                return (Expression<Func<T, S>>)ParseLambda(typeof(T), typeof(S), expression, values);
            }
    
            public static Type CreateClass(params DynamicProperty[] properties)
            {
                return ClassFactory.Instance.GetDynamicClass(properties);
            }
    
            public static Type CreateClass(IEnumerable<DynamicProperty> properties)
            {
                return ClassFactory.Instance.GetDynamicClass(properties);
            }
        }
    
        internal class DynamicOrdering
        {
            public Expression Selector;
            public bool Ascending;
        }
    
        internal class Signature : IEquatable<Signature>
        {
            public DynamicProperty[] properties;
            public int hashCode;
    
            public Signature(IEnumerable<DynamicProperty> properties)
            {
                this.properties = properties.ToArray();
                hashCode = 0;
                foreach (DynamicProperty p in properties)
                {
                    hashCode ^= p.Name.GetHashCode() ^ p.Type.GetHashCode();
                }
            }
    
            public override int GetHashCode()
            {
                return hashCode;
            }
    
            public override bool Equals(object obj)
            {
                return obj is Signature ? Equals((Signature)obj) : false;
            }
    
            public bool Equals(Signature other)
            {
                if (properties.Length != other.properties.Length) return false;
                for (int i = 0; i < properties.Length; i++)
                {
                    if (properties[i].Name != other.properties[i].Name ||
                        properties[i].Type != other.properties[i].Type) return false;
                }
                return true;
            }
        }
    
        internal class ClassFactory
        {
            public static readonly ClassFactory Instance = new ClassFactory();
    
            static ClassFactory() { }  // Trigger lazy initialization of static fields
    
            ModuleBuilder module;
            Dictionary<Signature, Type> classes;
            int classCount;
            ReaderWriterLock rwLock;
    
            private ClassFactory()
            {
                AssemblyName name = new AssemblyName("DynamicClasses");
                AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
    #if ENABLE_LINQ_PARTIAL_TRUST
                new ReflectionPermission(PermissionState.Unrestricted).Assert();
    #endif
                try
                {
                    module = assembly.DefineDynamicModule("Module");
                }
                finally
                {
    #if ENABLE_LINQ_PARTIAL_TRUST
                    PermissionSet.RevertAssert();
    #endif
                }
                classes = new Dictionary<Signature, Type>();
                rwLock = new ReaderWriterLock();
            }
    
            public Type GetDynamicClass(IEnumerable<DynamicProperty> properties)
            {
                rwLock.AcquireReaderLock(Timeout.Infinite);
                try
                {
                    Signature signature = new Signature(properties);
                    Type type;
                    if (!classes.TryGetValue(signature, out type))
                    {
                        type = CreateDynamicClass(signature.properties);
                        classes.Add(signature, type);
                    }
                    return type;
                }
                finally
                {
                    rwLock.ReleaseReaderLock();
                }
            }
    
            Type CreateDynamicClass(DynamicProperty[] properties)
            {
                LockCookie cookie = rwLock.UpgradeToWriterLock(Timeout.Infinite);
                try
                {
                    string typeName = "DynamicClass" + (classCount + 1);
    #if ENABLE_LINQ_PARTIAL_TRUST
                    new ReflectionPermission(PermissionState.Unrestricted).Assert();
    #endif
                    try
                    {
                        TypeBuilder tb = this.module.DefineType(typeName, TypeAttributes.Class |
                            TypeAttributes.Public, typeof(DynamicClass));
                        FieldInfo[] fields = GenerateProperties(tb, properties);
                        GenerateEquals(tb, fields);
                        GenerateGetHashCode(tb, fields);
                        Type result = tb.CreateType();
                        classCount++;
                        return result;
                    }
                    finally
                    {
    #if ENABLE_LINQ_PARTIAL_TRUST
                        PermissionSet.RevertAssert();
    #endif
                    }
                }
                finally
                {
                    rwLock.DowngradeFromWriterLock(ref cookie);
                }
            }
    
            FieldInfo[] GenerateProperties(TypeBuilder tb, DynamicProperty[] properties)
            {
                FieldInfo[] fields = new FieldBuilder[properties.Length];
                for (int i = 0; i < properties.Length; i++)
                {
                    DynamicProperty dp = properties[i];
                    FieldBuilder fb = tb.DefineField("_" + dp.Name, dp.Type, FieldAttributes.Private);
                    PropertyBuilder pb = tb.DefineProperty(dp.Name, PropertyAttributes.HasDefault, dp.Type, null);
                    MethodBuilder mbGet = tb.DefineMethod("get_" + dp.Name,
                        MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
                        dp.Type, Type.EmptyTypes);
                    ILGenerator genGet = mbGet.GetILGenerator();
                    genGet.Emit(OpCodes.Ldarg_0);
                    genGet.Emit(OpCodes.Ldfld, fb);
                    genGet.Emit(OpCodes.Ret);
                    MethodBuilder mbSet = tb.DefineMethod("set_" + dp.Name,
                        MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
                        null, new Type[] { dp.Type });
                    ILGenerator genSet = mbSet.GetILGenerator();
                    genSet.Emit(OpCodes.Ldarg_0);
                    genSet.Emit(OpCodes.Ldarg_1);
                    genSet.Emit(OpCodes.Stfld, fb);
                    genSet.Emit(OpCodes.Ret);
                    pb.SetGetMethod(mbGet);
                    pb.SetSetMethod(mbSet);
                    fields[i] = fb;
                }
                return fields;
            }
    
            void GenerateEquals(TypeBuilder tb, FieldInfo[] fields)
            {
                MethodBuilder mb = tb.DefineMethod("Equals",
                    MethodAttributes.Public | MethodAttributes.ReuseSlot |
                    MethodAttributes.Virtual | MethodAttributes.HideBySig,
                    typeof(bool), new Type[] { typeof(object) });
                ILGenerator gen = mb.GetILGenerator();
                LocalBuilder other = gen.DeclareLocal(tb);
                Label next = gen.DefineLabel();
                gen.Emit(OpCodes.Ldarg_1);
                gen.Emit(OpCodes.Isinst, tb);
                gen.Emit(OpCodes.Stloc, other);
                gen.Emit(OpCodes.Ldloc, other);
                gen.Emit(OpCodes.Brtrue_S, next);
                gen.Emit(OpCodes.Ldc_I4_0);
                gen.Emit(OpCodes.Ret);
                gen.MarkLabel(next);
                foreach (FieldInfo field in fields)
                {
                    Type ft = field.FieldType;
                    Type ct = typeof(EqualityComparer<>).MakeGenericType(ft);
                    next = gen.DefineLabel();
                    gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null);
                    gen.Emit(OpCodes.Ldarg_0);
                    gen.Emit(OpCodes.Ldfld, field);
                    gen.Emit(OpCodes.Ldloc, other);
                    gen.Emit(OpCodes.Ldfld, field);
                    gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("Equals", new Type[] { ft, ft }), null);
                    gen.Emit(OpCodes.Brtrue_S, next);
                    gen.Emit(OpCodes.Ldc_I4_0);
                    gen.Emit(OpCodes.Ret);
                    gen.MarkLabel(next);
                }
                gen.Emit(OpCodes.Ldc_I4_1);
                gen.Emit(OpCodes.Ret);
            }
    
            void GenerateGetHashCode(TypeBuilder tb, FieldInfo[] fields)
            {
                MethodBuilder mb = tb.DefineMethod("GetHashCode",
                    MethodAttributes.Public | MethodAttributes.ReuseSlot |
                    MethodAttributes.Virtual | MethodAttributes.HideBySig,
                    typeof(int), Type.EmptyTypes);
                ILGenerator gen = mb.GetILGenerator();
                gen.Emit(OpCodes.Ldc_I4_0);
                foreach (FieldInfo field in fields)
                {
                    Type ft = field.FieldType;
                    Type ct = typeof(EqualityComparer<>).MakeGenericType(ft);
                    gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null);
                    gen.Emit(OpCodes.Ldarg_0);
                    gen.Emit(OpCodes.Ldfld, field);
                    gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("GetHashCode", new Type[] { ft }), null);
                    gen.Emit(OpCodes.Xor);
                }
                gen.Emit(OpCodes.Ret);
            }
        }
    
        public sealed class ParseException : Exception
        {
            int position;
    
            public ParseException(string message, int position)
                : base(message)
            {
                this.position = position;
            }
    
            public int Position
            {
                get { return position; }
            }
    
            public override string ToString()
            {
                return string.Format(Res.ParseExceptionFormat, Message, position);
            }
        }
    
        internal class ExpressionParser
        {
            struct Token
            {
                public TokenId id;
                public string text;
                public int pos;
            }
    
            enum TokenId
            {
                Unknown,
                End,
                Identifier,
                StringLiteral,
                IntegerLiteral,
                RealLiteral,
                Exclamation,
                Percent,
                Amphersand,
                OpenParen,
                CloseParen,
                Asterisk,
                Plus,
                Comma,
                Minus,
                Dot,
                Slash,
                Colon,
                LessThan,
                Equal,
                GreaterThan,
                Question,
                OpenBracket,
                CloseBracket,
                Bar,
                ExclamationEqual,
                DoubleAmphersand,
                LessThanEqual,
                LessGreater,
                DoubleEqual,
                GreaterThanEqual,
                DoubleBar
            }
    
            interface ILogicalSignatures
            {
                void F(bool x, bool y);
                void F(bool? x, bool? y);
            }
    
            interface IArithmeticSignatures
            {
                void F(int x, int y);
                void F(uint x, uint y);
                void F(long x, long y);
                void F(ulong x, ulong y);
                void F(float x, float y);
                void F(double x, double y);
                void F(decimal x, decimal y);
                void F(int? x, int? y);
                void F(uint? x, uint? y);
                void F(long? x, long? y);
                void F(ulong? x, ulong? y);
                void F(float? x, float? y);
                void F(double? x, double? y);
                void F(decimal? x, decimal? y);
            }
    
            interface IRelationalSignatures : IArithmeticSignatures
            {
                void F(string x, string y);
                void F(char x, char y);
                void F(DateTime x, DateTime y);
                void F(TimeSpan x, TimeSpan y);
                void F(char? x, char? y);
                void F(DateTime? x, DateTime? y);
                void F(TimeSpan? x, TimeSpan? y);
            }
    
            interface IEqualitySignatures : IRelationalSignatures
            {
                void F(bool x, bool y);
                void F(bool? x, bool? y);
            }
    
            interface IAddSignatures : IArithmeticSignatures
            {
                void F(DateTime x, TimeSpan y);
                void F(TimeSpan x, TimeSpan y);
                void F(DateTime? x, TimeSpan? y);
                void F(TimeSpan? x, TimeSpan? y);
            }
    
            interface ISubtractSignatures : IAddSignatures
            {
                void F(DateTime x, DateTime y);
                void F(DateTime? x, DateTime? y);
            }
    
            interface INegationSignatures
            {
                void F(int x);
                void F(long x);
                void F(float x);
                void F(double x);
                void F(decimal x);
                void F(int? x);
                void F(long? x);
                void F(float? x);
                void F(double? x);
                void F(decimal? x);
            }
    
            interface INotSignatures
            {
                void F(bool x);
                void F(bool? x);
            }
    
            interface IEnumerableSignatures
            {
                void Where(bool predicate);
                void Any();
                void Any(bool predicate);
                void All(bool predicate);
                void Count();
                void Count(bool predicate);
                void Min(object selector);
                void Max(object selector);
                void Sum(int selector);
                void Sum(int? selector);
                void Sum(long selector);
                void Sum(long? selector);
                void Sum(float selector);
                void Sum(float? selector);
                void Sum(double selector);
                void Sum(double? selector);
                void Sum(decimal selector);
                void Sum(decimal? selector);
                void Average(int selector);
                void Average(int? selector);
                void Average(long selector);
                void Average(long? selector);
                void Average(float selector);
                void Average(float? selector);
                void Average(double selector);
                void Average(double? selector);
                void Average(decimal selector);
                void Average(decimal? selector);
            }
    
            static readonly Type[] predefinedTypes = {
                typeof(Object),
                typeof(Boolean),
                typeof(Char),
                typeof(String),
                typeof(SByte),
                typeof(Byte),
                typeof(Int16),
                typeof(UInt16),
                typeof(Int32),
                typeof(UInt32),
                typeof(Int64),
                typeof(UInt64),
                typeof(Single),
                typeof(Double),
                typeof(Decimal),
                typeof(DateTime),
                typeof(TimeSpan),
                typeof(Guid),
                typeof(Math),
                typeof(Convert)
            };
    
            static readonly Expression trueLiteral = Expression.Constant(true);
            static readonly Expression falseLiteral = Expression.Constant(false);
            static readonly Expression nullLiteral = Expression.Constant(null);
    
            static readonly string keywordIt = "it";
            static readonly string keywordIif = "iif";
            static readonly string keywordNew = "new";
    
            static Dictionary<string, object> keywords;
    
            Dictionary<string, object> symbols;
            IDictionary<string, object> externals;
            Dictionary<Expression, string> literals;
            ParameterExpression it;
            string text;
            int textPos;
            int textLen;
            char ch;
            Token token;
    
            public ExpressionParser(ParameterExpression[] parameters, string expression, object[] values)
            {
                if (expression == null) throw new ArgumentNullException("expression");
                if (keywords == null) keywords = CreateKeywords();
                symbols = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
                literals = new Dictionary<Expression, string>();
                if (parameters != null) ProcessParameters(parameters);
                if (values != null) ProcessValues(values);
                text = expression;
                textLen = text.Length;
                SetTextPos(0);
                NextToken();
            }
    
            void ProcessParameters(ParameterExpression[] parameters)
            {
                foreach (ParameterExpression pe in parameters)
                    if (!String.IsNullOrEmpty(pe.Name))
                        AddSymbol(pe.Name, pe);
                if (parameters.Length == 1 && String.IsNullOrEmpty(parameters[0].Name))
                    it = parameters[0];
            }
    
            void ProcessValues(object[] values)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    object value = values[i];
                    if (i == values.Length - 1 && value is IDictionary<string, object>)
                    {
                        externals = (IDictionary<string, object>)value;
                    }
                    else
                    {
                        AddSymbol("@" + i.ToString(System.Globalization.CultureInfo.InvariantCulture), value);
                    }
                }
            }
    
            void AddSymbol(string name, object value)
            {
                if (symbols.ContainsKey(name))
                    throw ParseError(Res.DuplicateIdentifier, name);
                symbols.Add(name, value);
            }
    
            public Expression Parse(Type resultType)
            {
                int exprPos = token.pos;
                Expression expr = ParseExpression();
                if (resultType != null)
                    if ((expr = PromoteExpression(expr, resultType, true)) == null)
                        throw ParseError(exprPos, Res.ExpressionTypeMismatch, GetTypeName(resultType));
                ValidateToken(TokenId.End, Res.SyntaxError);
                return expr;
            }
    
    #pragma warning disable 0219
            public IEnumerable<DynamicOrdering> ParseOrdering()
            {
                List<DynamicOrdering> orderings = new List<DynamicOrdering>();
                while (true)
                {
                    Expression expr = ParseExpression();
                    bool ascending = true;
                    if (TokenIdentifierIs("asc") || TokenIdentifierIs("ascending"))
                    {
                        NextToken();
                    }
                    else if (TokenIdentifierIs("desc") || TokenIdentifierIs("descending"))
                    {
                        NextToken();
                        ascending = false;
                    }
                    orderings.Add(new DynamicOrdering { Selector = expr, Ascending = ascending });
                    if (token.id != TokenId.Comma) break;
                    NextToken();
                }
                ValidateToken(TokenId.End, Res.SyntaxError);
                return orderings;
            }
    #pragma warning restore 0219
    
            // ?: operator
            Expression ParseExpression()
            {
                int errorPos = token.pos;
                Expression expr = ParseLogicalOr();
                if (token.id == TokenId.Question)
                {
                    NextToken();
                    Expression expr1 = ParseExpression();
                    ValidateToken(TokenId.Colon, Res.ColonExpected);
                    NextToken();
                    Expression expr2 = ParseExpression();
                    expr = GenerateConditional(expr, expr1, expr2, errorPos);
                }
                return expr;
            }
    
            // ||, or operator
            Expression ParseLogicalOr()
            {
                Expression left = ParseLogicalAnd();
                while (token.id == TokenId.DoubleBar || TokenIdentifierIs("or"))
                {
                    Token op = token;
                    NextToken();
                    Expression right = ParseLogicalAnd();
                    CheckAndPromoteOperands(typeof(ILogicalSignatures), op.text, ref left, ref right, op.pos);
                    left = Expression.OrElse(left, right);
                }
                return left;
            }
    
            // &&, and operator
            Expression ParseLogicalAnd()
            {
                Expression left = ParseComparison();
                while (token.id == TokenId.DoubleAmphersand || TokenIdentifierIs("and"))
                {
                    Token op = token;
                    NextToken();
                    Expression right = ParseComparison();
                    CheckAndPromoteOperands(typeof(ILogicalSignatures), op.text, ref left, ref right, op.pos);
                    left = Expression.AndAlso(left, right);
                }
                return left;
            }
    
            // =, ==, !=, <>, >, >=, <, <= operators
            Expression ParseComparison()
            {
                Expression left = ParseAdditive();
                while (token.id == TokenId.Equal || token.id == TokenId.DoubleEqual ||
                    token.id == TokenId.ExclamationEqual || token.id == TokenId.LessGreater ||
                    token.id == TokenId.GreaterThan || token.id == TokenId.GreaterThanEqual ||
                    token.id == TokenId.LessThan || token.id == TokenId.LessThanEqual)
                {
                    Token op = token;
                    NextToken();
                    Expression right = ParseAdditive();
                    bool isEquality = op.id == TokenId.Equal || op.id == TokenId.DoubleEqual ||
                        op.id == TokenId.ExclamationEqual || op.id == TokenId.LessGreater;
                    if (isEquality && !left.Type.IsValueType && !right.Type.IsValueType)
                    {
                        if (left.Type != right.Type)
                        {
                            if (left.Type.IsAssignableFrom(right.Type))
                            {
                                right = Expression.Convert(right, left.Type);
                            }
                            else if (right.Type.IsAssignableFrom(left.Type))
                            {
                                left = Expression.Convert(left, right.Type);
                            }
                            else
                            {
                                throw IncompatibleOperandsError(op.text, left, right, op.pos);
                            }
                        }
                    }
                    else if (IsEnumType(left.Type) || IsEnumType(right.Type))
                    {
                        if (left.Type != right.Type)
                        {
                            Expression e;
                            if ((e = PromoteExpression(right, left.Type, true)) != null)
                            {
                                right = e;
                            }
                            else if ((e = PromoteExpression(left, right.Type, true)) != null)
                            {
                                left = e;
                            }
                            else
                            {
                                throw IncompatibleOperandsError(op.text, left, right, op.pos);
                            }
                        }
                    }
                    else
                    {
                        CheckAndPromoteOperands(isEquality ? typeof(IEqualitySignatures) : typeof(IRelationalSignatures),
                            op.text, ref left, ref right, op.pos);
                    }
                    switch (op.id)
                    {
                        case TokenId.Equal:
                        case TokenId.DoubleEqual:
                            left = GenerateEqual(left, right);
                            break;
                        case TokenId.ExclamationEqual:
                        case TokenId.LessGreater:
                            left = GenerateNotEqual(left, right);
                            break;
                        case TokenId.GreaterThan:
                            left = GenerateGreaterThan(left, right);
                            break;
                        case TokenId.GreaterThanEqual:
                            left = GenerateGreaterThanEqual(left, right);
                            break;
                        case TokenId.LessThan:
                            left = GenerateLessThan(left, right);
                            break;
                        case TokenId.LessThanEqual:
                            left = GenerateLessThanEqual(left, right);
                            break;
                    }
                }
                return left;
            }
    
            // +, -, & operators
            Expression ParseAdditive()
            {
                Expression left = ParseMultiplicative();
                while (token.id == TokenId.Plus || token.id == TokenId.Minus ||
                    token.id == TokenId.Amphersand)
                {
                    Token op = token;
                    NextToken();
                    Expression right = ParseMultiplicative();
                    switch (op.id)
                    {
                        case TokenId.Plus:
                            if (left.Type == typeof(string) || right.Type == typeof(string))
                                goto case TokenId.Amphersand;
                            CheckAndPromoteOperands(typeof(IAddSignatures), op.text, ref left, ref right, op.pos);
                            left = GenerateAdd(left, right);
                            break;
                        case TokenId.Minus:
                            CheckAndPromoteOperands(typeof(ISubtractSignatures), op.text, ref left, ref right, op.pos);
                            left = GenerateSubtract(left, right);
                            break;
                        case TokenId.Amphersand:
                            left = GenerateStringConcat(left, right);
                            break;
                    }
                }
                return left;
            }
    
            // *, /, %, mod operators
            Expression ParseMultiplicative()
            {
                Expression left = ParseUnary();
                while (token.id == TokenId.Asterisk || token.id == TokenId.Slash ||
                    token.id == TokenId.Percent || TokenIdentifierIs("mod"))
                {
                    Token op = token;
                    NextToken();
                    Expression right = ParseUnary();
                    CheckAndPromoteOperands(typeof(IArithmeticSignatures), op.text, ref left, ref right, op.pos);
                    switch (op.id)
                    {
                        case TokenId.Asterisk:
                            left = Expression.Multiply(left, right);
                            break;
                        case TokenId.Slash:
                            left = Expression.Divide(left, right);
                            break;
                        case TokenId.Percent:
                        case TokenId.Identifier:
                            left = Expression.Modulo(left, right);
                            break;
                    }
                }
                return left;
            }
    
            // -, !, not unary operators
            Expression ParseUnary()
            {
                if (token.id == TokenId.Minus || token.id == TokenId.Exclamation ||
                    TokenIdentifierIs("not"))
                {
                    Token op = token;
                    NextToken();
                    if (op.id == TokenId.Minus && (token.id == TokenId.IntegerLiteral ||
                        token.id == TokenId.RealLiteral))
                    {
                        token.text = "-" + token.text;
                        token.pos = op.pos;
                        return ParsePrimary();
                    }
                    Expression expr = ParseUnary();
                    if (op.id == TokenId.Minus)
                    {
                        CheckAndPromoteOperand(typeof(INegationSignatures), op.text, ref expr, op.pos);
                        expr = Expression.Negate(expr);
                    }
                    else
                    {
                        CheckAndPromoteOperand(typeof(INotSignatures), op.text, ref expr, op.pos);
                        expr = Expression.Not(expr);
                    }
                    return expr;
                }
                return ParsePrimary();
            }
    
            Expression ParsePrimary()
            {
                Expression expr = ParsePrimaryStart();
                while (true)
                {
                    if (token.id == TokenId.Dot)
                    {
                        NextToken();
                        expr = ParseMemberAccess(null, expr);
                    }
                    else if (token.id == TokenId.OpenBracket)
                    {
                        expr = ParseElementAccess(expr);
                    }
                    else
                    {
                        break;
                    }
                }
                return expr;
            }
    
            Expression ParsePrimaryStart()
            {
                switch (token.id)
                {
                    case TokenId.Identifier:
                        return ParseIdentifier();
                    case TokenId.StringLiteral:
                        return ParseStringLiteral();
                    case TokenId.IntegerLiteral:
                        return ParseIntegerLiteral();
                    case TokenId.RealLiteral:
                        return ParseRealLiteral();
                    case TokenId.OpenParen:
                        return ParseParenExpression();
                    default:
                        throw ParseError(Res.ExpressionExpected);
                }
            }
    
            Expression ParseStringLiteral()
            {
                ValidateToken(TokenId.StringLiteral);
                char quote = token.text[0];
                string s = token.text.Substring(1, token.text.Length - 2);
                int start = 0;
                while (true)
                {
                    int i = s.IndexOf(quote, start);
                    if (i < 0) break;
                    s = s.Remove(i, 1);
                    start = i + 1;
                }
                if (quote == '\'')
                {
                    if (s.Length != 1)
                        throw ParseError(Res.InvalidCharacterLiteral);
                    NextToken();
                    return CreateLiteral(s[0], s);
                }
                NextToken();
                return CreateLiteral(s, s);
            }
    
            Expression ParseIntegerLiteral()
            {
                ValidateToken(TokenId.IntegerLiteral);
                string text = token.text;
                if (text[0] != '-')
                {
                    ulong value;
                    if (!UInt64.TryParse(text, out value))
                        throw ParseError(Res.InvalidIntegerLiteral, text);
                    NextToken();
                    if (value <= (ulong)Int32.MaxValue) return CreateLiteral((int)value, text);
                    if (value <= (ulong)UInt32.MaxValue) return CreateLiteral((uint)value, text);
                    if (value <= (ulong)Int64.MaxValue) return CreateLiteral((long)value, text);
                    return CreateLiteral(value, text);
                }
                else
                {
                    long value;
                    if (!Int64.TryParse(text, out value))
                        throw ParseError(Res.InvalidIntegerLiteral, text);
                    NextToken();
                    if (value >= Int32.MinValue && value <= Int32.MaxValue)
                        return CreateLiteral((int)value, text);
                    return CreateLiteral(value, text);
                }
            }
    
            Expression ParseRealLiteral()
            {
                ValidateToken(TokenId.RealLiteral);
                string text = token.text;
                object value = null;
                char last = text[text.Length - 1];
                if (last == 'F' || last == 'f')
                {
                    float f;
                    if (Single.TryParse(text.Substring(0, text.Length - 1), out f)) value = f;
                }
                else
                {
                    double d;
                    if (Double.TryParse(text, out d)) value = d;
                }
                if (value == null) throw ParseError(Res.InvalidRealLiteral, text);
                NextToken();
                return CreateLiteral(value, text);
            }
    
            Expression CreateLiteral(object value, string text)
            {
                ConstantExpression expr = Expression.Constant(value);
                literals.Add(expr, text);
                return expr;
            }
    
            Expression ParseParenExpression()
            {
                ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
                NextToken();
                Expression e = ParseExpression();
                ValidateToken(TokenId.CloseParen, Res.CloseParenOrOperatorExpected);
                NextToken();
                return e;
            }
    
            Expression ParseIdentifier()
            {
                ValidateToken(TokenId.Identifier);
                object value;
                if (keywords.TryGetValue(token.text, out value))
                {
                    if (value is Type) return ParseTypeAccess((Type)value);
                    if (value == (object)keywordIt) return ParseIt();
                    if (value == (object)keywordIif) return ParseIif();
                    if (value == (object)keywordNew) return ParseNew();
                    NextToken();
                    return (Expression)value;
                }
                if (symbols.TryGetValue(token.text, out value) ||
                    externals != null && externals.TryGetValue(token.text, out value))
                {
                    Expression expr = value as Expression;
                    if (expr == null)
                    {
                        expr = Expression.Constant(value);
                    }
                    else
                    {
                        LambdaExpression lambda = expr as LambdaExpression;
                        if (lambda != null) return ParseLambdaInvocation(lambda);
                    }
                    NextToken();
                    return expr;
                }
                if (it != null) return ParseMemberAccess(null, it);
                throw ParseError(Res.UnknownIdentifier, token.text);
            }
    
            Expression ParseIt()
            {
                if (it == null)
                    throw ParseError(Res.NoItInScope);
                NextToken();
                return it;
            }
    
            Expression ParseIif()
            {
                int errorPos = token.pos;
                NextToken();
                Expression[] args = ParseArgumentList();
                if (args.Length != 3)
                    throw ParseError(errorPos, Res.IifRequiresThreeArgs);
                return GenerateConditional(args[0], args[1], args[2], errorPos);
            }
    
            Expression GenerateConditional(Expression test, Expression expr1, Expression expr2, int errorPos)
            {
                if (test.Type != typeof(bool))
                    throw ParseError(errorPos, Res.FirstExprMustBeBool);
                if (expr1.Type != expr2.Type)
                {
                    Expression expr1as2 = expr2 != nullLiteral ? PromoteExpression(expr1, expr2.Type, true) : null;
                    Expression expr2as1 = expr1 != nullLiteral ? PromoteExpression(expr2, expr1.Type, true) : null;
                    if (expr1as2 != null && expr2as1 == null)
                    {
                        expr1 = expr1as2;
                    }
                    else if (expr2as1 != null && expr1as2 == null)
                    {
                        expr2 = expr2as1;
                    }
                    else
                    {
                        string type1 = expr1 != nullLiteral ? expr1.Type.Name : "null";
                        string type2 = expr2 != nullLiteral ? expr2.Type.Name : "null";
                        if (expr1as2 != null && expr2as1 != null)
                            throw ParseError(errorPos, Res.BothTypesConvertToOther, type1, type2);
                        throw ParseError(errorPos, Res.NeitherTypeConvertsToOther, type1, type2);
                    }
                }
                return Expression.Condition(test, expr1, expr2);
            }
    
            Expression ParseNew()
            {
                NextToken();
                ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
                NextToken();
                List<DynamicProperty> properties = new List<DynamicProperty>();
                List<Expression> expressions = new List<Expression>();
                while (true)
                {
                    int exprPos = token.pos;
                    Expression expr = ParseExpression();
                    string propName;
                    if (TokenIdentifierIs("as"))
                    {
                        NextToken();
                        propName = GetIdentifier();
                        NextToken();
                    }
                    else
                    {
                        MemberExpression me = expr as MemberExpression;
                        if (me == null) throw ParseError(exprPos, Res.MissingAsClause);
                        propName = me.Member.Name;
                    }
                    expressions.Add(expr);
                    properties.Add(new DynamicProperty(propName, expr.Type));
                    if (token.id != TokenId.Comma) break;
                    NextToken();
                }
                ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected);
                NextToken();
                Type type = DynamicExpression.CreateClass(properties);
                MemberBinding[] bindings = new MemberBinding[properties.Count];
                for (int i = 0; i < bindings.Length; i++)
                    bindings[i] = Expression.Bind(type.GetProperty(properties[i].Name), expressions[i]);
                return Expression.MemberInit(Expression.New(type), bindings);
            }
    
            Expression ParseLambdaInvocation(LambdaExpression lambda)
            {
                int errorPos = token.pos;
                NextToken();
                Expression[] args = ParseArgumentList();
                MethodBase method;
                if (FindMethod(lambda.Type, "Invoke", false, args, out method) != 1)
                    throw ParseError(errorPos, Res.ArgsIncompatibleWithLambda);
                return Expression.Invoke(lambda, args);
            }
    
            Expression ParseTypeAccess(Type type)
            {
                int errorPos = token.pos;
                NextToken();
                if (token.id == TokenId.Question)
                {
                    if (!type.IsValueType || IsNullableType(type))
                        throw ParseError(errorPos, Res.TypeHasNoNullableForm, GetTypeName(type));
                    type = typeof(Nullable<>).MakeGenericType(type);
                    NextToken();
                }
                if (token.id == TokenId.OpenParen)
                {
                    Expression[] args = ParseArgumentList();
                    MethodBase method;
                    switch (FindBestMethod(type.GetConstructors(), args, out method))
                    {
                        case 0:
                            if (args.Length == 1)
                                return GenerateConversion(args[0], type, errorPos);
                            throw ParseError(errorPos, Res.NoMatchingConstructor, GetTypeName(type));
                        case 1:
                            return Expression.New((ConstructorInfo)method, args);
                        default:
                            throw ParseError(errorPos, Res.AmbiguousConstructorInvocation, GetTypeName(type));
                    }
                }
                ValidateToken(TokenId.Dot, Res.DotOrOpenParenExpected);
                NextToken();
                return ParseMemberAccess(type, null);
            }
    
            Expression GenerateConversion(Expression expr, Type type, int errorPos)
            {
                Type exprType = expr.Type;
                if (exprType == type) return expr;
                if (exprType.IsValueType && type.IsValueType)
                {
                    if ((IsNullableType(exprType) || IsNullableType(type)) &&
                        GetNonNullableType(exprType) == GetNonNullableType(type))
                        return Expression.Convert(expr, type);
                    if ((IsNumericType(exprType) || IsEnumType(exprType)) &&
                        (IsNumericType(type)) || IsEnumType(type))
                        return Expression.ConvertChecked(expr, type);
                }
                if (exprType.IsAssignableFrom(type) || type.IsAssignableFrom(exprType) ||
                    exprType.IsInterface || type.IsInterface)
                    return Expression.Convert(expr, type);
                throw ParseError(errorPos, Res.CannotConvertValue,
                    GetTypeName(exprType), GetTypeName(type));
            }
    
            Expression ParseMemberAccess(Type type, Expression instance)
            {
                if (instance != null) type = instance.Type;
                int errorPos = token.pos;
                string id = GetIdentifier();
                NextToken();
                if (token.id == TokenId.OpenParen)
                {
                    if (instance != null && type != typeof(string))
                    {
                        Type enumerableType = FindGenericType(typeof(IEnumerable<>), type);
                        if (enumerableType != null)
                        {
                            Type elementType = enumerableType.GetGenericArguments()[0];
                            return ParseAggregate(instance, elementType, id, errorPos);
                        }
                    }
                    Expression[] args = ParseArgumentList();
                    MethodBase mb;
                    switch (FindMethod(type, id, instance == null, args, out mb))
                    {
                        case 0:
                            throw ParseError(errorPos, Res.NoApplicableMethod,
                                id, GetTypeName(type));
                        case 1:
                            MethodInfo method = (MethodInfo)mb;
                            if (!IsPredefinedType(method.DeclaringType))
                                throw ParseError(errorPos, Res.MethodsAreInaccessible, GetTypeName(method.DeclaringType));
                            if (method.ReturnType == typeof(void))
                                throw ParseError(errorPos, Res.MethodIsVoid,
                                    id, GetTypeName(method.DeclaringType));
                            return Expression.Call(instance, (MethodInfo)method, args);
                        default:
                            throw ParseError(errorPos, Res.AmbiguousMethodInvocation,
                                id, GetTypeName(type));
                    }
                }
                else
                {
                    MemberInfo member = FindPropertyOrField(type, id, instance == null);
                    if (member == null)
                        throw ParseError(errorPos, Res.UnknownPropertyOrField,
                            id, GetTypeName(type));
                    return member is PropertyInfo ?
                        Expression.Property(instance, (PropertyInfo)member) :
                        Expression.Field(instance, (FieldInfo)member);
                }
            }
    
            static Type FindGenericType(Type generic, Type type)
            {
                while (type != null && type != typeof(object))
                {
                    if (type.IsGenericType && type.GetGenericTypeDefinition() == generic) return type;
                    if (generic.IsInterface)
                    {
                        foreach (Type intfType in type.GetInterfaces())
                        {
                            Type found = FindGenericType(generic, intfType);
                            if (found != null) return found;
                        }
                    }
                    type = type.BaseType;
                }
                return null;
            }
    
            Expression ParseAggregate(Expression instance, Type elementType, string methodName, int errorPos)
            {
                ParameterExpression outerIt = it;
                ParameterExpression innerIt = Expression.Parameter(elementType, "");
                it = innerIt;
                Expression[] args = ParseArgumentList();
                it = outerIt;
                MethodBase signature;
                if (FindMethod(typeof(IEnumerableSignatures), methodName, false, args, out signature) != 1)
                    throw ParseError(errorPos, Res.NoApplicableAggregate, methodName);
                Type[] typeArgs;
                if (signature.Name == "Min" || signature.Name == "Max")
                {
                    typeArgs = new Type[] { elementType, args[0].Type };
                }
                else
                {
                    typeArgs = new Type[] { elementType };
                }
                if (args.Length == 0)
                {
                    args = new Expression[] { instance };
                }
                else
                {
                    args = new Expression[] { instance, Expression.Lambda(args[0], innerIt) };
                }
                return Expression.Call(typeof(Enumerable), signature.Name, typeArgs, args);
            }
    
            Expression[] ParseArgumentList()
            {
                ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
                NextToken();
                Expression[] args = token.id != TokenId.CloseParen ? ParseArguments() : new Expression[0];
                ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected);
                NextToken();
                return args;
            }
    
            Expression[] ParseArguments()
            {
                List<Expression> argList = new List<Expression>();
                while (true)
                {
                    argList.Add(ParseExpression());
                    if (token.id != TokenId.Comma) break;
                    NextToken();
                }
                return argList.ToArray();
            }
    
            Expression ParseElementAccess(Expression expr)
            {
                int errorPos = token.pos;
                ValidateToken(TokenId.OpenBracket, Res.OpenParenExpected);
                NextToken();
                Expression[] args = ParseArguments();
                ValidateToken(TokenId.CloseBracket, Res.CloseBracketOrCommaExpected);
                NextToken();
                if (expr.Type.IsArray)
                {
                    if (expr.Type.GetArrayRank() != 1 || args.Length != 1)
                        throw ParseError(errorPos, Res.CannotIndexMultiDimArray);
                    Expression index = PromoteExpression(args[0], typeof(int), true);
                    if (index == null)
                        throw ParseError(errorPos, Res.InvalidIndex);
                    return Expression.ArrayIndex(expr, index);
                }
                else
                {
                    MethodBase mb;
                    switch (FindIndexer(expr.Type, args, out mb))
                    {
                        case 0:
                            throw ParseError(errorPos, Res.NoApplicableIndexer,
                                GetTypeName(expr.Type));
                        case 1:
                            return Expression.Call(expr, (MethodInfo)mb, args);
                        default:
                            throw ParseError(errorPos, Res.AmbiguousIndexerInvocation,
                                GetTypeName(expr.Type));
                    }
                }
            }
    
            static bool IsPredefinedType(Type type)
            {
                foreach (Type t in predefinedTypes) if (t == type) return true;
                return false;
            }
    
            static bool IsNullableType(Type type)
            {
                return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
            }
    
            static Type GetNonNullableType(Type type)
            {
                return IsNullableType(type) ? type.GetGenericArguments()[0] : type;
            }
    
            static string GetTypeName(Type type)
            {
                Type baseType = GetNonNullableType(type);
                string s = baseType.Name;
                if (type != baseType) s += '?';
                return s;
            }
    
            static bool IsNumericType(Type type)
            {
                return GetNumericTypeKind(type) != 0;
            }
    
            static bool IsSignedIntegralType(Type type)
            {
                return GetNumericTypeKind(type) == 2;
            }
    
            static bool IsUnsignedIntegralType(Type type)
            {
                return GetNumericTypeKind(type) == 3;
            }
    
            static int GetNumericTypeKind(Type type)
            {
                type = GetNonNullableType(type);
                if (type.IsEnum) return 0;
                switch (Type.GetTypeCode(type))
                {
                    case TypeCode.Char:
                    case TypeCode.Single:
                    case TypeCode.Double:
                    case TypeCode.Decimal:
                        return 1;
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.Int32:
                    case TypeCode.Int64:
                        return 2;
                    case TypeCode.Byte:
                    case TypeCode.UInt16:
                    case TypeCode.UInt32:
                    case TypeCode.UInt64:
                        return 3;
                    default:
                        return 0;
                }
            }
    
            static bool IsEnumType(Type type)
            {
                return GetNonNullableType(type).IsEnum;
            }
    
            void CheckAndPromoteOperand(Type signatures, string opName, ref Expression expr, int errorPos)
            {
                Expression[] args = new Expression[] { expr };
                MethodBase method;
                if (FindMethod(signatures, "F", false, args, out method) != 1)
                    throw ParseError(errorPos, Res.IncompatibleOperand,
                        opName, GetTypeName(args[0].Type));
                expr = args[0];
            }
    
            void CheckAndPromoteOperands(Type signatures, string opName, ref Expression left, ref Expression right, int errorPos)
            {
                Expression[] args = new Expression[] { left, right };
                MethodBase method;
                if (FindMethod(signatures, "F", false, args, out method) != 1)
                    throw IncompatibleOperandsError(opName, left, right, errorPos);
                left = args[0];
                right = args[1];
            }
    
            Exception IncompatibleOperandsError(string opName, Expression left, Expression right, int pos)
            {
                return ParseError(pos, Res.IncompatibleOperands,
                    opName, GetTypeName(left.Type), GetTypeName(right.Type));
            }
    
            MemberInfo FindPropertyOrField(Type type, string memberName, bool staticAccess)
            {
                BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly |
                    (staticAccess ? BindingFlags.Static : BindingFlags.Instance);
                foreach (Type t in SelfAndBaseTypes(type))
                {
                    MemberInfo[] members = t.FindMembers(MemberTypes.Property | MemberTypes.Field,
                        flags, Type.FilterNameIgnoreCase, memberName);
                    if (members.Length != 0) return members[0];
                }
                return null;
            }
    
            int FindMethod(Type type, string methodName, bool staticAccess, Expression[] args, out MethodBase method)
            {
                BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly |
                    (staticAccess ? BindingFlags.Static : BindingFlags.Instance);
                foreach (Type t in SelfAndBaseTypes(type))
                {
                    MemberInfo[] members = t.FindMembers(MemberTypes.Method,
                        flags, Type.FilterNameIgnoreCase, methodName);
                    int count = FindBestMethod(members.Cast<MethodBase>(), args, out method);
                    if (count != 0) return count;
                }
                method = null;
                return 0;
            }
    
            int FindIndexer(Type type, Expression[] args, out MethodBase method)
            {
                foreach (Type t in SelfAndBaseTypes(type))
                {
                    MemberInfo[] members = t.GetDefaultMembers();
                    if (members.Length != 0)
                    {
                        IEnumerable<MethodBase> methods = members.
                            OfType<PropertyInfo>().
                            Select(p => (MethodBase)p.GetGetMethod()).
                            Where(m => m != null);
                        int count = FindBestMethod(methods, args, out method);
                        if (count != 0) return count;
                    }
                }
                method = null;
                return 0;
            }
    
            static IEnumerable<Type> SelfAndBaseTypes(Type type)
            {
                if (type.IsInterface)
                {
                    List<Type> types = new List<Type>();
                    AddInterface(types, type);
                    return types;
                }
                return SelfAndBaseClasses(type);
            }
    
            static IEnumerable<Type> SelfAndBaseClasses(Type type)
            {
                while (type != null)
                {
                    yield return type;
                    type = type.BaseType;
                }
            }
    
            static void AddInterface(List<Type> types, Type type)
            {
                if (!types.Contains(type))
                {
                    types.Add(type);
                    foreach (Type t in type.GetInterfaces()) AddInterface(types, t);
                }
            }
    
            class MethodData
            {
                public MethodBase MethodBase;
                public ParameterInfo[] Parameters;
                public Expression[] Args;
            }
    
            int FindBestMethod(IEnumerable<MethodBase> methods, Expression[] args, out MethodBase method)
            {
                MethodData[] applicable = methods.
                    Select(m => new MethodData { MethodBase = m, Parameters = m.GetParameters() }).
                    Where(m => IsApplicable(m, args)).
                    ToArray();
                if (applicable.Length > 1)
                {
                    applicable = applicable.
                        Where(m => applicable.All(n => m == n || IsBetterThan(args, m, n))).
                        ToArray();
                }
                if (applicable.Length == 1)
                {
                    MethodData md = applicable[0];
                    for (int i = 0; i < args.Length; i++) args[i] = md.Args[i];
                    method = md.MethodBase;
                }
                else
                {
                    method = null;
                }
                return applicable.Length;
            }
    
            bool IsApplicable(MethodData method, Expression[] args)
            {
                if (method.Parameters.Length != args.Length) return false;
                Expression[] promotedArgs = new Expression[args.Length];
                for (int i = 0; i < args.Length; i++)
                {
                    ParameterInfo pi = method.Parameters[i];
                    if (pi.IsOut) return false;
                    Expression promoted = PromoteExpression(args[i], pi.ParameterType, false);
                    if (promoted == null) return false;
                    promotedArgs[i] = promoted;
                }
                method.Args = promotedArgs;
                return true;
            }
    
            Expression PromoteExpression(Expression expr, Type type, bool exact)
            {
                if (expr.Type == type) return expr;
                if (expr is ConstantExpression)
                {
                    ConstantExpression ce = (ConstantExpression)expr;
                    if (ce == nullLiteral)
                    {
                        if (!type.IsValueType || IsNullableType(type))
                            return Expression.Constant(null, type);
                    }
                    else
                    {
                        string text;
                        if (literals.TryGetValue(ce, out text))
                        {
                            Type target = GetNonNullableType(type);
                            Object value = null;
                            switch (Type.GetTypeCode(ce.Type))
                            {
                                case TypeCode.Int32:
                                case TypeCode.UInt32:
                                case TypeCode.Int64:
                                case TypeCode.UInt64:
                                    value = ParseNumber(text, target);
                                    break;
                                case TypeCode.Double:
                                    if (target == typeof(decimal)) value = ParseNumber(text, target);
                                    break;
                                case TypeCode.String:
                                    value = ParseEnum(text, target);
                                    break;
                            }
                            if (value != null)
                                return Expression.Constant(value, type);
                        }
                    }
                }
                if (IsCompatibleWith(expr.Type, type))
                {
                    if (type.IsValueType || exact) return Expression.Convert(expr, type);
                    return expr;
                }
                return null;
            }
    
            static object ParseNumber(string text, Type type)
            {
                switch (Type.GetTypeCode(GetNonNullableType(type)))
                {
                    case TypeCode.SByte:
                        sbyte sb;
                        if (sbyte.TryParse(text, out sb)) return sb;
                        break;
                    case TypeCode.Byte:
                        byte b;
                        if (byte.TryParse(text, out b)) return b;
                        break;
                    case TypeCode.Int16:
                        short s;
                        if (short.TryParse(text, out s)) return s;
                        break;
                    case TypeCode.UInt16:
                        ushort us;
                        if (ushort.TryParse(text, out us)) return us;
                        break;
                    case TypeCode.Int32:
                        int i;
                        if (int.TryParse(text, out i)) return i;
                        break;
                    case TypeCode.UInt32:
                        uint ui;
                        if (uint.TryParse(text, out ui)) return ui;
                        break;
                    case TypeCode.Int64:
                        long l;
                        if (long.TryParse(text, out l)) return l;
                        break;
                    case TypeCode.UInt64:
                        ulong ul;
                        if (ulong.TryParse(text, out ul)) return ul;
                        break;
                    case TypeCode.Single:
                        float f;
                        if (float.TryParse(text, out f)) return f;
                        break;
                    case TypeCode.Double:
                        double d;
                        if (double.TryParse(text, out d)) return d;
                        break;
                    case TypeCode.Decimal:
                        decimal e;
                        if (decimal.TryParse(text, out e)) return e;
                        break;
                }
                return null;
            }
    
            static object ParseEnum(string name, Type type)
            {
                if (type.IsEnum)
                {
                    MemberInfo[] memberInfos = type.FindMembers(MemberTypes.Field,
                        BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static,
                        Type.FilterNameIgnoreCase, name);
                    if (memberInfos.Length != 0) return ((FieldInfo)memberInfos[0]).GetValue(null);
                }
                return null;
            }
    
            static bool IsCompatibleWith(Type source, Type target)
            {
                if (source == target) return true;
                if (!target.IsValueType) return target.IsAssignableFrom(source);
                Type st = GetNonNullableType(source);
                Type tt = GetNonNullableType(target);
                if (st != source && tt == target) return false;
                TypeCode sc = st.IsEnum ? TypeCode.Object : Type.GetTypeCode(st);
                TypeCode tc = tt.IsEnum ? TypeCode.Object : Type.GetTypeCode(tt);
                switch (sc)
                {
                    case TypeCode.SByte:
                        switch (tc)
                        {
                            case TypeCode.SByte:
                            case TypeCode.Int16:
                            case TypeCode.Int32:
                            case TypeCode.Int64:
                            case TypeCode.Single:
                            case TypeCode.Double:
                            case TypeCode.Decimal:
                                return true;
                        }
                        break;
                    case TypeCode.Byte:
                        switch (tc)
                        {
                            case TypeCode.Byte:
                            case TypeCode.Int16:
                            case TypeCode.UInt16:
                            case TypeCode.Int32:
                            case TypeCode.UInt32:
                            case TypeCode.Int64:
                            case TypeCode.UInt64:
                            case TypeCode.Single:
                            case TypeCode.Double:
                            case TypeCode.Decimal:
                                return true;
                        }
                        break;
                    case TypeCode.Int16:
                        switch (tc)
                        {
                            case TypeCode.Int16:
                            case TypeCode.Int32:
                            case TypeCode.Int64:
                            case TypeCode.Single:
                            case TypeCode.Double:
                            case TypeCode.Decimal:
                                return true;
                        }
                        break;
                    case TypeCode.UInt16:
                        switch (tc)
                        {
                            case TypeCode.UInt16:
                            case TypeCode.Int32:
                            case TypeCode.UInt32:
                            case TypeCode.Int64:
                            case TypeCode.UInt64:
                            case TypeCode.Single:
                            case TypeCode.Double:
                            case TypeCode.Decimal:
                                return true;
                        }
                        break;
                    case TypeCode.Int32:
                        switch (tc)
                        {
                            case TypeCode.Int32:
                            case TypeCode.Int64:
                            case TypeCode.Single:
                            case TypeCode.Double:
                            case TypeCode.Decimal:
                                return true;
                        }
                        break;
                    case TypeCode.UInt32:
                        switch (tc)
                        {
                            case TypeCode.UInt32:
                            case TypeCode.Int64:
                            case TypeCode.UInt64:
                            case TypeCode.Single:
                            case TypeCode.Double:
                            case TypeCode.Decimal:
                                return true;
                        }
                        break;
                    case TypeCode.Int64:
                        switch (tc)
                        {
                            case TypeCode.Int64:
                            case TypeCode.Single:
                            case TypeCode.Double:
                            case TypeCode.Decimal:
                                return true;
                        }
                        break;
                    case TypeCode.UInt64:
                        switch (tc)
                        {
                            case TypeCode.UInt64:
                            case TypeCode.Single:
                            case TypeCode.Double:
                            case TypeCode.Decimal:
                                return true;
                        }
                        break;
                    case TypeCode.Single:
                        switch (tc)
                        {
                            case TypeCode.Single:
                            case TypeCode.Double:
                                return true;
                        }
                        break;
                    default:
                        if (st == tt) return true;
                        break;
                }
                return false;
            }
    
            static bool IsBetterThan(Expression[] args, MethodData m1, MethodData m2)
            {
                bool better = false;
                for (int i = 0; i < args.Length; i++)
                {
                    int c = CompareConversions(args[i].Type,
                        m1.Parameters[i].ParameterType,
                        m2.Parameters[i].ParameterType);
                    if (c < 0) return false;
                    if (c > 0) better = true;
                }
                return better;
            }
    
            // Return 1 if s -> t1 is a better conversion than s -> t2
            // Return -1 if s -> t2 is a better conversion than s -> t1
            // Return 0 if neither conversion is better
            static int CompareConversions(Type s, Type t1, Type t2)
            {
                if (t1 == t2) return 0;
                if (s == t1) return 1;
                if (s == t2) return -1;
                bool t1t2 = IsCompatibleWith(t1, t2);
                bool t2t1 = IsCompatibleWith(t2, t1);
                if (t1t2 && !t2t1) return 1;
                if (t2t1 && !t1t2) return -1;
                if (IsSignedIntegralType(t1) && IsUnsignedIntegralType(t2)) return 1;
                if (IsSignedIntegralType(t2) && IsUnsignedIntegralType(t1)) return -1;
                return 0;
            }
    
            Expression GenerateEqual(Expression left, Expression right)
            {
                return Expression.Equal(left, right);
            }
    
            Expression GenerateNotEqual(Expression left, Expression right)
            {
                return Expression.NotEqual(left, right);
            }
    
            Expression GenerateGreaterThan(Expression left, Expression right)
            {
                if (left.Type == typeof(string))
                {
                    return Expression.GreaterThan(
                        GenerateStaticMethodCall("Compare", left, right),
                        Expression.Constant(0)
                    );
                }
                return Expression.GreaterThan(left, right);
            }
    
            Expression GenerateGreaterThanEqual(Expression left, Expression right)
            {
                if (left.Type == typeof(string))
                {
                    return Expression.GreaterThanOrEqual(
                        GenerateStaticMethodCall("Compare", left, right),
                        Expression.Constant(0)
                    );
                }
                return Expression.GreaterThanOrEqual(left, right);
            }
    
            Expression GenerateLessThan(Expression left, Expression right)
            {
                if (left.Type == typeof(string))
                {
                    return Expression.LessThan(
                        GenerateStaticMethodCall("Compare", left, right),
                        Expression.Constant(0)
                    );
                }
                return Expression.LessThan(left, right);
            }
    
            Expression GenerateLessThanEqual(Expression left, Expression right)
            {
                if (left.Type == typeof(string))
                {
                    return Expression.LessThanOrEqual(
                        GenerateStaticMethodCall("Compare", left, right),
                        Expression.Constant(0)
                    );
                }
                return Expression.LessThanOrEqual(left, right);
            }
    
            Expression GenerateAdd(Expression left, Expression right)
            {
                if (left.Type == typeof(string) && right.Type == typeof(string))
                {
                    return GenerateStaticMethodCall("Concat", left, right);
                }
                return Expression.Add(left, right);
            }
    
            Expression GenerateSubtract(Expression left, Expression right)
            {
                return Expression.Subtract(left, right);
            }
    
            Expression GenerateStringConcat(Expression left, Expression right)
            {
                return Expression.Call(
                    null,
                    typeof(string).GetMethod("Concat", new[] { typeof(object), typeof(object) }),
                    new[] { left, right });
            }
    
            MethodInfo GetStaticMethod(string methodName, Expression left, Expression right)
            {
                return left.Type.GetMethod(methodName, new[] { left.Type, right.Type });
            }
    
            Expression GenerateStaticMethodCall(string methodName, Expression left, Expression right)
            {
                return Expression.Call(null, GetStaticMethod(methodName, left, right), new[] { left, right });
            }
    
            void SetTextPos(int pos)
            {
                textPos = pos;
                ch = textPos < textLen ? text[textPos] : '\0';
            }
    
            void NextChar()
            {
                if (textPos < textLen) textPos++;
                ch = textPos < textLen ? text[textPos] : '\0';
            }
    
            void NextToken()
            {
                while (Char.IsWhiteSpace(ch)) NextChar();
                TokenId t;
                int tokenPos = textPos;
                switch (ch)
                {
                    case '!':
                        NextChar();
                        if (ch == '=')
                        {
                            NextChar();
                            t = TokenId.ExclamationEqual;
                        }
                        else
                        {
                            t = TokenId.Exclamation;
                        }
                        break;
                    case '%':
                        NextChar();
                        t = TokenId.Percent;
                        break;
                    case '&':
                        NextChar();
                        if (ch == '&')
                        {
                            NextChar();
                            t = TokenId.DoubleAmphersand;
                        }
                        else
                        {
                            t = TokenId.Amphersand;
                        }
                        break;
                    case '(':
                        NextChar();
                        t = TokenId.OpenParen;
                        break;
                    case ')':
                        NextChar();
                        t = TokenId.CloseParen;
                        break;
                    case '*':
                        NextChar();
                        t = TokenId.Asterisk;
                        break;
                    case '+':
                        NextChar();
                        t = TokenId.Plus;
                        break;
                    case ',':
                        NextChar();
                        t = TokenId.Comma;
                        break;
                    case '-':
                        NextChar();
                        t = TokenId.Minus;
                        break;
                    case '.':
                        NextChar();
                        t = TokenId.Dot;
                        break;
                    case '/':
                        NextChar();
                        t = TokenId.Slash;
                        break;
                    case ':':
                        NextChar();
                        t = TokenId.Colon;
                        break;
                    case '<':
                        NextChar();
                        if (ch == '=')
                        {
                            NextChar();
                            t = TokenId.LessThanEqual;
                        }
                        else if (ch == '>')
                        {
                            NextChar();
                            t = TokenId.LessGreater;
                        }
                        else
                        {
                            t = TokenId.LessThan;
                        }
                        break;
                    case '=':
                        NextChar();
                        if (ch == '=')
                        {
                            NextChar();
                            t = TokenId.DoubleEqual;
                        }
                        else
                        {
                            t = TokenId.Equal;
                        }
                        break;
                    case '>':
                        NextChar();
                        if (ch == '=')
                        {
                            NextChar();
                            t = TokenId.GreaterThanEqual;
                        }
                        else
                        {
                            t = TokenId.GreaterThan;
                        }
                        break;
                    case '?':
                        NextChar();
                        t = TokenId.Question;
                        break;
                    case '[':
                        NextChar();
                        t = TokenId.OpenBracket;
                        break;
                    case ']':
                        NextChar();
                        t = TokenId.CloseBracket;
                        break;
                    case '|':
                        NextChar();
                        if (ch == '|')
                        {
                            NextChar();
                            t = TokenId.DoubleBar;
                        }
                        else
                        {
                            t = TokenId.Bar;
                        }
                        break;
                    case '"':
                    case '\'':
                        char quote = ch;
                        do
                        {
                            NextChar();
                            while (textPos < textLen && ch != quote) NextChar();
                            if (textPos == textLen)
                                throw ParseError(textPos, Res.UnterminatedStringLiteral);
                            NextChar();
                        } while (ch == quote);
                        t = TokenId.StringLiteral;
                        break;
                    default:
                        if (Char.IsLetter(ch) || ch == '@' || ch == '_')
                        {
                            do
                            {
                                NextChar();
                            } while (Char.IsLetterOrDigit(ch) || ch == '_');
                            t = TokenId.Identifier;
                            break;
                        }
                        if (Char.IsDigit(ch))
                        {
                            t = TokenId.IntegerLiteral;
                            do
                            {
                                NextChar();
                            } while (Char.IsDigit(ch));
                            if (ch == '.')
                            {
                                t = TokenId.RealLiteral;
                                NextChar();
                                ValidateDigit();
                                do
                                {
                                    NextChar();
                                } while (Char.IsDigit(ch));
                            }
                            if (ch == 'E' || ch == 'e')
                            {
                                t = TokenId.RealLiteral;
                                NextChar();
                                if (ch == '+' || ch == '-') NextChar();
                                ValidateDigit();
                                do
                                {
                                    NextChar();
                                } while (Char.IsDigit(ch));
                            }
                            if (ch == 'F' || ch == 'f') NextChar();
                            break;
                        }
                        if (textPos == textLen)
                        {
                            t = TokenId.End;
                            break;
                        }
                        throw ParseError(textPos, Res.InvalidCharacter, ch);
                }
                token.id = t;
                token.text = text.Substring(tokenPos, textPos - tokenPos);
                token.pos = tokenPos;
            }
    
            bool TokenIdentifierIs(string id)
            {
                return token.id == TokenId.Identifier && String.Equals(id, token.text, StringComparison.OrdinalIgnoreCase);
            }
    
            string GetIdentifier()
            {
                ValidateToken(TokenId.Identifier, Res.IdentifierExpected);
                string id = token.text;
                if (id.Length > 1 && id[0] == '@') id = id.Substring(1);
                return id;
            }
    
            void ValidateDigit()
            {
                if (!Char.IsDigit(ch)) throw ParseError(textPos, Res.DigitExpected);
            }
    
            void ValidateToken(TokenId t, string errorMessage)
            {
                if (token.id != t) throw ParseError(errorMessage);
            }
    
            void ValidateToken(TokenId t)
            {
                if (token.id != t) throw ParseError(Res.SyntaxError);
            }
    
            Exception ParseError(string format, params object[] args)
            {
                return ParseError(token.pos, format, args);
            }
    
            Exception ParseError(int pos, string format, params object[] args)
            {
                return new ParseException(string.Format(System.Globalization.CultureInfo.CurrentCulture, format, args), pos);
            }
    
            static Dictionary<string, object> CreateKeywords()
            {
                Dictionary<string, object> d = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
                d.Add("true", trueLiteral);
                d.Add("false", falseLiteral);
                d.Add("null", nullLiteral);
                d.Add(keywordIt, keywordIt);
                d.Add(keywordIif, keywordIif);
                d.Add(keywordNew, keywordNew);
                foreach (Type type in predefinedTypes) d.Add(type.Name, type);
                return d;
            }
        }
    
        static class Res
        {
            public const string DuplicateIdentifier = "The identifier '{0}' was defined more than once";
            public const string ExpressionTypeMismatch = "Expression of type '{0}' expected";
            public const string ExpressionExpected = "Expression expected";
            public const string InvalidCharacterLiteral = "Character literal must contain exactly one character";
            public const string InvalidIntegerLiteral = "Invalid integer literal '{0}'";
            public const string InvalidRealLiteral = "Invalid real literal '{0}'";
            public const string UnknownIdentifier = "Unknown identifier '{0}'";
            public const string NoItInScope = "No 'it' is in scope";
            public const string IifRequiresThreeArgs = "The 'iif' function requires three arguments";
            public const string FirstExprMustBeBool = "The first expression must be of type 'Boolean'";
            public const string BothTypesConvertToOther = "Both of the types '{0}' and '{1}' convert to the other";
            public const string NeitherTypeConvertsToOther = "Neither of the types '{0}' and '{1}' converts to the other";
            public const string MissingAsClause = "Expression is missing an 'as' clause";
            public const string ArgsIncompatibleWithLambda = "Argument list incompatible with lambda expression";
            public const string TypeHasNoNullableForm = "Type '{0}' has no nullable form";
            public const string NoMatchingConstructor = "No matching constructor in type '{0}'";
            public const string AmbiguousConstructorInvocation = "Ambiguous invocation of '{0}' constructor";
            public const string CannotConvertValue = "A value of type '{0}' cannot be converted to type '{1}'";
            public const string NoApplicableMethod = "No applicable method '{0}' exists in type '{1}'";
            public const string MethodsAreInaccessible = "Methods on type '{0}' are not accessible";
            public const string MethodIsVoid = "Method '{0}' in type '{1}' does not return a value";
            public const string AmbiguousMethodInvocation = "Ambiguous invocation of method '{0}' in type '{1}'";
            public const string UnknownPropertyOrField = "No property or field '{0}' exists in type '{1}'";
            public const string NoApplicableAggregate = "No applicable aggregate method '{0}' exists";
            public const string CannotIndexMultiDimArray = "Indexing of multi-dimensional arrays is not supported";
            public const string InvalidIndex = "Array index must be an integer expression";
            public const string NoApplicableIndexer = "No applicable indexer exists in type '{0}'";
            public const string AmbiguousIndexerInvocation = "Ambiguous invocation of indexer in type '{0}'";
            public const string IncompatibleOperand = "Operator '{0}' incompatible with operand type '{1}'";
            public const string IncompatibleOperands = "Operator '{0}' incompatible with operand types '{1}' and '{2}'";
            public const string UnterminatedStringLiteral = "Unterminated string literal";
            public const string InvalidCharacter = "Syntax error '{0}'";
            public const string DigitExpected = "Digit expected";
            public const string SyntaxError = "Syntax error";
            public const string TokenExpected = "{0} expected";
            public const string ParseExceptionFormat = "{0} (at index {1})";
            public const string ColonExpected = "':' expected";
            public const string OpenParenExpected = "'(' expected";
            public const string CloseParenOrOperatorExpected = "')' or operator expected";
            public const string CloseParenOrCommaExpected = "')' or ',' expected";
            public const string DotOrOpenParenExpected = "'.' or '(' expected";
            public const string OpenBracketExpected = "'[' expected";
            public const string CloseBracketOrCommaExpected = "']' or ',' expected";
            public const string IdentifierExpected = "Identifier expected";
        }
    }

    3.         创建运行服务的宿主程序。实际开发中,通常选择创建一个windows服务程序来运行Remoting,但是服务需要安装才能启动,运行和调试起来都比较繁琐,所以这里创建一个简单的控制台程序来运行它。在解决方案下添加一个控制台程序项目,在program.cs编写如下代码:

     

     

    View Code
    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Runtime.Remoting;

    using System.Runtime.Remoting.Channels;

    using System.Runtime.Remoting.Channels.Tcp;



    namespace EFServiceHost

    {

    class Program

    {

    staticvoid Main(string[] args)

    {

    ChannelServices.RegisterChannel(
    new TcpChannel(9932),false);

    RemotingConfiguration.ApplicationName
    ="EFService"; RemotingConfiguration.RegisterActivatedServiceType(typeof(EFService.ServiceFactory));

    Console.WriteLine(
    "Start Server,Press any key to exit.");

    Console.ReadLine();

    }

    }

    }

     

    配置文件App.Config主要包括数据库连接信息以及自己定义一个数据上下文名称(这里和数据库连接名称相同,事实上不必相同),数据库连接信息可以从EFModel项目中配置文件中直接拷贝过来。内容如下:

     

    View Code
    <?xml version="1.0" encoding="utf-8"?>

    <configuration>

    <connectionStrings>

    <add name="SchoolEntities" connectionString="metadata=res://*/EFModel.csdl|res://*/EFModel.ssdl|res://*/EFModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=192.168.0.110\SQLEXPRESS;Initial Catalog=School;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient">

    </add>

    </connectionStrings>

    <appSettings >

    <add key="SchoolEntities" value="EFModel.SchoolEntities, EFModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>

    </appSettings>

    </configuration>

     

    编译成功后,拷贝EFModel和和EFService两个项目生成的dll文件至可执行文件EFServiceHost.exe同一目录下,点击运行EFServiceHost.exe 

     

    4.         最后,我们建立一个winform客户端作为测试。在program.cs注册远程服务:

     

    View Code
    staticvoid Main()

    {

    Application.EnableVisualStyles();

    Application.SetCompatibleTextRenderingDefault(
    false);



    //注册远程服务

    RemotingConfiguration.RegisterActivatedClientType(

    typeof(ServiceFactory), "tcp://localhost:9932/EFService");



    Application.Run(
    new Form1());

    }

     

    添加一个窗体Form1,放入一个按钮,在按钮点击处理事件里加入下面的代码,示范客户端如何调用远程服务类实现查询和CUD操作,简单起见,我不演示数据库的数据变化了,反正,看代码,你懂的。 

     

     

    View Code
    privatevoid button1_Click(object sender, EventArgs e)

    {

    //通过远程服务工厂创建出远程服务对象,注意此处构造函数的参

    注意此处参
    // 数值为远程服务器上配置文件上的数据上下文名称

    ServiceFactory factory
    =new ServiceFactory();

    IEntityHelper entityHelper
    = factory.CreateEntityHelper("SchoolEntities");



    //查询实体

    List
    <Course> courses = entityHelper.Query<Course>("CourseID>@0",0);

    Course course
    = courses.SingleOrDefault(p => p.CourseID ==1045);



    //修改实体

    course.Title
    ="update succeed";

    entityHelper.Save(course);



    //删除实体

    entityHelper.Delete(course);



    //新增实体

    entityHelper.Save(
    new Course() { Title ="new course" });



    }

     

    四、             部署应用 

    1.         至此,整个系统搭建完毕。在本例中,我把所有项目都统一建立在一个解决方案下,其实是为了演示方便,实际开发时候,完全可以各自独立创建。下面我们来分析一下各个项目的职能和相互之间的引用关系。 

    1)        EFModel:由Visual Studio 的数据模型工具生成的数据库实例模型,提供数据的查询以及CUD操作。不需引用其它项目。 

    2)        EFService:使用数据库实例模型以及实体的抽象基类编写完成,代码里不涉及具体数据库模型实例,运行时通过客户端注入参数和读取配置文件动态生成数据库模型实例,并调用实例的查询和CUD方法实现客户端的请求。不需引用其它项目。 

    3)        EFServiceHost:负责运行Remoting服务,如果通过配置文件方式发布服务的话,编译时也不需引用其它项目,我这里引用了EFService项目,是因为使用了代码方式暴露EFSservice的服务类。运行时需要将EFServiceEFModeldll文件拷贝至运行目录下。 

    4)        EFClient:需要引用EFModelEFService(注:因为本例中式使用了Remoting作为远程服务,如果是WebService或者WCF则只需添加服务引用,然后在本地生成客户端代理类)。事实上EFService中的实现类EntityHelper也可以独立出去,不必让客户端引用,对于客户端而言,仅仅是使用ServiceFactory和接口IentityHelper就足够了。这样只要接口不变, EntityHelper更新的时候,客户端无须更新引用,而且服务端代码可以完全被隔离开客户端,对一些服务端和客户端之间的保密性比较敏感的项目尤为有利。 

     

    2.         通过分析我们发现,在开发下一个新项目的时候,即使整个数据库都变了,从SQL SERVER变成Oracle,数据库服务名变了,表也变了,我们仍然无需修改服务端代码,只需针对新的数据库,生成新的EFModel,然后拷贝DLL文件至EFServiceHost的运行目录下(这也就是我为什么要把EFModel独立成一个项目的原因),再修改一下EFServiceHost的配置文件中的数据库连接和实体容器名称即可完成新系统的部署。对于客户端来说,也就是更新一下EFModel.dll,还是调用服务端提供的那几个API,便可完成查询和CUD操作,不用关心底层的数据库是SQL Server还是Oracle,更不用自己实现对新库新表的查询和CUD操作(本来也不用)。当然,对于正在运行的系统,我们也可以针对新建数据库生成新的实体模型DLL,拷贝至EFServiceHost运行目录下,实现热插拔方式扩展数据库,而对原来的系统毫无影响,即使新加的库是不同类型的库。 

     

    五、             系统架构图示

      

     

    六、             总结 

    从以上分析可以看出,该系统运用到项目开发中,对服务端来说,实现了最大程度组件重用(零代码修改),对客户端开发来说,高度简化了对数据的操作命令,并封装了实现细节,大大降低了开发的技术难度,提高了开发速度。当然,我这里写的代码仅仅是最简单的演示代码,在实际项目开发中,服务端要处理的细节和扩展的功能要比这复杂得多。比如性能优化,实现复杂查询和批量CUD操作,并发处理,事务控制,日志跟踪,数据缓存等等。另外,如果各层采用不同的技术实现,服务层实现的代码也有差异。比如EF可以选择最新版的更完善更强大的EF4.0,远程服务可以选择Remoting,WebService,WCF等,不同的远程服务,宿主程序也有所不同,RemotingWCF可以选择winform,控制台程序,IIS,而Web Service只能选择IIS。不同的服务,不同的宿主程序,会有不同的通信通道 (Http,Tcp),不同的数据传输格式 (二进制,XML,JSON)。如果你嫌上面的实现方式涉及的技术太多,开发起来太麻烦,那么,微软现成的具有REST风格的远程数据服务WCF Data Services会是你的最佳选择。WCF Data Services由于只用Http方式通信,用XMLJSON格式传输数据,性能上会比用Tcp通信二进制格式传输的性能差一些,但是相信在将来基于SOA的分布式系统大行其道时,WCF Data Services会是.net实现SOA框架的主流技术,这里基于篇幅所限,不作详细介绍了,MSDN上有这方面的很详尽的技术参考文档,有兴趣的读者可以自行参阅。 

     

    补充源码打包下载

     

  • 相关阅读:
    Apache的Order Allow,Deny 详解
    apache的AllowOverride以及Options使用详解
    安装启动apache2.4后报Invalid command 'order', perhaps misspelled or defined by a module not included
    前端常见跨域解决方案(全)
    php面试宝典
    php面试题2018
    nginx负载均衡的5种策略
    多台服务器共享session问题
    小程序定义并使用类
    微信小程序真机预览接口不到数据,打开调试确能请求到
  • 原文地址:https://www.cnblogs.com/lindping/p/2004834.html
Copyright © 2020-2023  润新知