一对多映射关系
/// <summary>
/// 一对多连接查询
/// </summary>
/// <typeparam name="FirstT">主键表实体类型</typeparam>
/// <typeparam name="SecondT">外键表实体类型</typeparam>
/// <typeparam name="ReturnT">返回的实体类型(一般如果实体中存在映射关系的时候返回类型与主键表类型基本相同)</typeparam>
/// <param name="sqlStr">连接查询的sql</param>
/// <param name="ForeignKeyName">主键表实体中的的外键表集合名称</param>
/// <param name="Name">外键表中的外键名</param>
/// <returns></returns>
public static List<FirstT> SelectOneToMore<FirstT, SecondT, ReturnT>(string sqlStr, string ForeignKeyName, string Name) where FirstT : IDataEntity, new()
{
using (var conn = ConnectionFactory.Connection)
{
List<FirstT> list = new List<FirstT>();
var lookUp = new Dictionary<int, FirstT>();
list = conn.Query<FirstT, SecondT, FirstT>(sqlStr,
(firstT, secondT) =>
{
FirstT t;
if (!lookUp.TryGetValue(firstT.ID, out t))
{
lookUp.Add(firstT.ID, t = firstT);
}
foreach (var item in firstT.GetType().GetProperties())
{
if (item.Name == ForeignKeyName)
{
var a = item.GetValue(firstT, null) as HashSet<SecondT>;
a.Add(secondT);
}
}
//t.GetType().GetMember(ForeignKeyName)
return firstT;
}, null, null, true, Name, null, null).ToList(); return list;
} }
一对一映射关系
/// <summary>
/// 一对一链接查询
/// </summary>
/// <typeparam name="FirstT">主键表类型</typeparam>
/// <typeparam name="SecondT">外键表类型</typeparam>
/// <typeparam name="ReturnT">返回值类型</typeparam>
/// <param name="sqlStr">sql</param>
/// <param name="ForeignKeyName">主键表实体中的的外键表集合名称</param>
/// <param name="Name">外键表中的外键名</param>
/// <returns></returns>
public static List<FirstT> SelectOneToOne<FirstT, SecondT, ReturnT>(string sqlStr, string ForeignKeyName, string Name)
where FirstT : IDataEntity, new()
where SecondT : class,IDataEntity, new()
{
using (var conn = ConnectionFactory.Connection)
{
List<FirstT> list = new List<FirstT>();
var lookUp = new Dictionary<int, FirstT>();
list = conn.Query<FirstT, SecondT, FirstT>(sqlStr,
(firstT, secondT) =>
{
foreach (var item in firstT.GetType().GetProperties())
{
if (item.Name == ForeignKeyName)
{
item.SetValue(firstT, item.GetValue(firstT, null));
}
}
//t.GetType().GetMember(ForeignKeyName)
return firstT;
}, null, null, true, Name, null, null).ToList(); return list;
} }