选择FluentData,主要看中其可以自动将sql查询结果映射为指定对象。
举个例子来讲:
public class Deal
{
public int DealId { get; set; }
public string Title { get; set; }
public int FKProviderid { get; set; }
public virtual Provider Provider { get; set; }
}
public class Provider
{
public int ProviderId { get; set; }
public string Name { get; set; }
}
使用FluentData如下的语句:
DbContext.Sql("select a.*,b.Name as Provider_Name from Deal a inner join Provider b on a.FKProviderId=b.ProviderId").QueryMany<Deal>();
返回一个List<Deal>并且每个Deal对象的Provider属性都会自动创建为Provider对象,并且为对象的Name赋值
FluentData可以下载到源码,但代码太多不好理解,我在下面实现了sqldatareader映射的功能,大概可以体现FluentData的实现方式:
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
/// <summary>
/// 反射辅助类
/// </summary>
public static class ReflectionHelper
{
private static readonly ConcurrentDictionary<Type, Dictionary<string, PropertyInfo>> _cachedProperties
= new ConcurrentDictionary<Type, Dictionary<string, PropertyInfo>>();
public static object GetPropertyValue(object item, PropertyInfo property)
{
var value = property.GetValue(item, null);
return value;
}
public static Dictionary<string, PropertyInfo> GetProperties(Type type)
{
var properties = _cachedProperties.GetOrAdd(type, BuildPropertyDictionary);
return properties;
}
private static Dictionary<string, PropertyInfo> BuildPropertyDictionary(Type type)
{
var result = new Dictionary<string, PropertyInfo>();
var properties = type.Get