在上一篇《DataReader轉(zhuǎn)換為List的一種實現(xiàn)》文章中我構(gòu)建了一個IDataReader得擴展
public static IEnumerable<T> GetEnumerator<T>(this IDataReader reader,Func<IDataRecord, T> generator)
這個擴展時接受一個委托類型的參數(shù)實現(xiàn)DataReader轉(zhuǎn)換為對應(yīng)的實體類,而這個委托所執(zhí)行的方法便是下圖的實現(xiàn):
public static QuestionNotifyInfo CreateQuestionNotifyInfo(IDataRecord record)
{
return new QuestionNotifyInfo
{
QID = record.Field<int>("QID"),
Title = record.Field<string>("Title"),
AnswerID = record.Field<int>("AnswerID"),
UserID = record.Field<int>("UserID"),
UserName = record.Field<string>("UserName"),
Content = record.Field<string>("Content"),
DateAdded = record.Field<DateTime>("DateAdded"),
NotifyType=record.Field<int>("NotifyType")
};
}
如果項目中想要使用上一篇《DataReader轉(zhuǎn)換為List的一種實現(xiàn)》文章中方案的話,每一個實體類都必須實現(xiàn)一個類似上圖中的轉(zhuǎn)換實體方法,雖然我們可以使用代碼生成的方式
為每個類實現(xiàn)上訴方法,但不知為何,總是感覺這樣的做法還是太機械,而且代碼也太丑陋,為此必須尋找一種更好的方法。
觀察所有實體類的轉(zhuǎn)換方法,可以看出這些方法有類似的地方,可以抽象為如下的“模板”:
r => new T
{
Property1 = r.Field<Type[Property1]>("Property1"),
Property2 = r.Field<Type[Property2]>("Property2"),
…
}
能不能使用System.Linq.Expressions API中的方法動態(tài)生成這些方法呢?答案是肯定
結(jié)合我這里的實際情況實現(xiàn)的代碼如下:
public static Func<IDataRecord, T> DynamicCreateEntity<T>()
{
// Compiles a delegate of the form (IDataRecord r) => new T { Prop1 = r.Field<Prop1Type>("Prop1"), ... }
ParameterExpression r = Expression.Parameter(typeof(IDataRecord), "r");
// Create property bindings for all writable properties
List<MemberBinding> bindings = new List<MemberBinding>();
foreach (PropertyInfo property in (typeof(T).GetProperties()))
{
// Create expression representing r.Field<property.PropertyType>(property.Name)
MethodCallExpression propertyValue = Expression.Call(
typeof(DatabaseExtend).GetMethod("Field").MakeGenericMethod(property.PropertyType),
r, Expression.Constant(property.Name));
// Assign the property value to property through a member binding
MemberBinding binding = Expression.Bind(property, propertyValue);
bindings.Add(binding);
}
// Create the initializer, which instantiates an instance of T and sets property values
// using the member bindings we just created
Expression initializer = Expression.MemberInit(Expression.New(typeof(T)), bindings);
// Create the lambda expression, which represents the complete delegate (r => initializer)
Expression<Func<IDataRecord, T>> lambda = Expression.Lambda<Func<IDataRecord, T>>(
initializer, r);
return lambda.Compile();
}
有了上面的方法之后,現(xiàn)在我們必要為每個實體類都增加一個裝換的方法了,所有現(xiàn)在我們可以更加簡化我們的數(shù)據(jù)訪問層的操作了,繼續(xù)擴展數(shù)據(jù)庫訪問類,添加下面兩個擴展方法:
public static IList<T> ExecuteStoredProc<T>(this Database dataBase, string storedProcedureName, params object[] parameterValues)
{
IList<T> result = null;
using (IDataReader dr=dataBase.ExecuteReaderStoredProc(storedProcedureName,parameterValues))
{
result = dr.GetEnumerator(DynamicCreateEntity<T>()).ToList();
}
return result;
}
public static IList<T> ExecuteSqlStringc<T>(this Database dataBase, string formatSqlString, params object[] parameterValues)
{
IList<T> result = null;
using (IDataReader dr = dataBase.ExecuteReaderSqlString(formatSqlString, parameterValues))
{
result = dr.GetEnumerator(DynamicCreateEntity<T>()).ToList();
}
return result;
}
主要參考文章 Using LINQ Expressions to Generate Dynamic Methods
如對本文有疑問,請?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會為你解答?。?點擊進入論壇