close
文章出處

      正如ORM名稱所指示的,實現ORM的關鍵點在于解決“對象--關系”之間的映射,例如,如何將一個DataRow轉換為一個Entity Object,又如何將一個對某Entity Object的操作映射到一個IDbCommand,等等。我們以DataRabbit為例,在DataRabbit中,使用IORMapping接口來抽象這些映射:

    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);
                    
continue;
                }

                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.Nop);
            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表達式方案)。

 

 

 

 

 

 

     

 


不含病毒。www.avast.com
arrow
arrow
    全站熱搜

    AutoPoster 發表在 痞客邦 留言(0) 人氣()