天天看點

實作ORM的四種方案

    public interface IORMapping<TEntity>

    {

        TEntity GetEntityFrom(DataRow row ,bool withBlob);

        /// <summary>

        /// FillParameterValue  使用entity的内容填充command中的各個IDbDataParameter的參數值。

        /// </summary>      

        void FillParameterValue(IDbCommand command, TEntity entity);

     }

     關于如何實作IORMapping接口,至少有四種方案。我們以實作GetEntityFrom方法為例為例來講述這四種方案,這個方法是将一個DataRow轉換為一個Entity Object。

1.代碼生成器

     現在有很多代碼生成器可以直接生成實作了ORM功能的DAL層,其背後的原理是,根據資料表的大綱(如有哪些列、每個列的類型等資訊)來生成對應的實作了IORMapping接口的類。代碼生成器是在編譯之前就完成了這些工作的。

2.反射

     将一個DataRow轉換為一個Entity Object,如果粒度更細一點,我們實際要解決的是如何将DataRow的一列的值指派給Entity Object對應的屬性,我們可以使用反射在運作時給Entity Object的屬性指派,如:

entityType.InvokeMember(columnName, BindingFlags.Public | BindingFlags.IgnoreCase |

                        BindingFlags.Instance | BindingFlags.SetProperty, null, entity, row[columnName]);

     這行代碼的含義是将row中【columnName】列的值指派給entity對象的【columnName】屬性。

3.Emit

     我們可以在運作時根據每個Entity類型動态發射對應的實作了IORMapping接口的類型,這些動态類型發射成功後,便可以被執行個體化然後被使用。比如我們要發射實作GetEntityFrom方法的代碼:

private void EmitGetEntityFromMethod(TypeBuilder typeBuilder, MethodInfo baseMethod, Type entityType, DataSchema dataSchema)

        {

            MethodBuilder methodBuilder = typeBuilder.DefineMethod("GetEntityFrom", baseMethod.Attributes & ~MethodAttributes.Abstract, baseMethod.CallingConvention, baseMethod.ReturnType, EmitHelper.GetParametersType(baseMethod));

            ILGenerator ilGenerator = methodBuilder.GetILGenerator();

            Label retLabel = ilGenerator.DefineLabel();

            ilGenerator.DeclareLocal(entityType); //Member member = null ;

            ilGenerator.Emit(OpCodes.Nop);

            ilGenerator.Emit(OpCodes.Newobj, entityType.GetConstructor(new Type[] { }));

            ilGenerator.Emit(OpCodes.Stloc_0); //member = new Member() ;

            IList<PropertyInfo> blobList = new List<PropertyInfo>();

            #region 為非blob屬性指派

            foreach (PropertyInfo property in entityType.GetProperties())

            {

                ColumnSchema columnSchema = dataSchema.GetColumnSchema(property.Name);

                if (columnSchema == null)

                {

                    continue;

                }

                if ((property.PropertyType == typeof(byte[])) && (!columnSchema.IsTimestamp))

                    blobList.Add(property);

                EmitSetProperty(entityType, ilGenerator, property);

            }

            #endregion

            if (blobList.Count > 0)

                ilGenerator.Emit(OpCodes.Ldarg_2);

                ilGenerator.Emit(OpCodes.Brfalse, retLabel);

                #region 為blob屬性指派

                foreach (PropertyInfo property in blobList)

                    EmitSetProperty(entityType, ilGenerator, property);

                #endregion

            ilGenerator.MarkLabel(retLabel);

            ilGenerator.Emit(OpCodes.Ldloc_0);

            ilGenerator.Emit(OpCodes.Ret);

            typeBuilder.DefineMethodOverride(methodBuilder, baseMethod);    // 定義方法重載

        }

4.使用Lamda表達式

     如果是在.NET3.5上,我們可以使用動态生成的Lamda表達式來完成Entity Object屬性的指派操作,關鍵點是要如何生成用于指派的動态委托。比如:

 private Action<TEntity, object> CreateFunctionOfSetProperty<TEntity>(MethodInfo setPropertyMethod, Type columnType)

            ParameterExpression paramEntityObj = Expression.Parameter(typeof(TEntity), "entity");

            ParameterExpression paramProVal = Expression.Parameter(typeof(object), "propertyVal");

            UnaryExpression paramProVal2 = Expression.Convert(paramProVal, columnType);

            MethodCallExpression body = Expression.Call(paramEntityObj, setPropertyMethod, paramProVal2);

            Expression<Action<TEntity, object>> setPropertyExpression = Expression.Lambda<Action<TEntity, object>>(body, paramEntityObj, paramProVal);

            Action<TEntity, object> setPropertyAction = setPropertyExpression.Compile();

            return (entity, propertyVal) => { setPropertyAction(entity, propertyVal); };

        } 

     這個方法傳回一個委托,傳回的委托接收兩個參數--Entity Object 和要賦的屬性值,調用這個委托便可以為Entity Object的某個屬性進行指派。

     好了,四種方案已經簡單介紹完畢,下面我們來比較一下。

(1)除了第一種方案是在編譯期完成外,後面三種方案都是在運作期完成的。

(2)第一種方案的效率是最高的,但是所需的手工操作也是最多的(比如每次修改了表結構都需要重新生成DAL層)。第二種方案的效率是最低的,反射使效率的折損非常之大。後兩種方案的效率都不錯(幾乎接近第一種方案)。

(3)Emit方案的實作難度應當是最大的,其次是Lamda表達式方案。

(4)Lamda表達式方案在.NET3.5及以上平台才可使用。

     DataRabbit 3.x及之前版本采用的是Emit方案,後續的4.0及以上版本則對Emit方案和Lamda表達式方案都支援(預設為Emit方案,可以修改配置選項使之采用Lamda表達式方案)。