我的功能如下:
public IEnumerable<Member> Members(Member models)
{
string query = "SELECT a.[Name], b.[MemberStatus] FROM [Member] a WITH (NOLOCK) INNER JOIN [MemberStatus] b WITH (NOLOCK) ON a.[ID] = b.[ID]";
using (IDbConnection conn = new SqlConnection(ConfigurationManager.AppSettings["MyConnection"]))
{
conn.Open();
return conn.Query<Member, MemberStatus, Member>(query, (member, memberStatus) =>
{
member.MemberStatus = memberStatus;
return member;
}).ToList();
}
}
现在我想创建一个可以重复使用的泛型函数,因为代码类似的代码将超过1(来自dapper的映射)。
以下是我为上述代码制作的可重复使用的代码:
public TReturn Queries<TParent, TChild, TReturn>(string query, Func<TParent, TChild, TReturn> map, object arguments)
{
using (IDbConnection conn = new SqlConnection(ConfigurationManager.AppSettings["MyConnection"]))
{
conn.Open();
return conn.Query<TParent, TChild, TReturn>(query, (parent, child) =>
{
// not sure on how to pass from here
return parent;
});
}
}
我可以在会员中调用这样的函数:
public IEnumerable<Member> Members(Member models)
{
string query = "SELECT a.[Name], b.[MemberStatus] FROM [Member] a WITH (NOLOCK) INNER JOIN [MemberStatus] b WITH (NOLOCK) ON a.[ID] = b.[ID]";
return Helper.Queries<Member, MemberStatus, Member>(query, (member, memberStatus) => member.MemberStauts = memberStatus);
}
但我不确定如何将member.MemberStatus
或member.MemberStatus
以外的其他变量传递给我所做的Queries
函数。要么是{{1}或者在Dapper中的QueryMultiple
我的做法是否正确?或任何其他建议?
由于
答案 0 :(得分:0)
我尝试了1小时后解决了自己的问题,下面是解决方案:
例如,泛型函数位于另一个名为Helper
的类上,并且您希望从另一个类DataAccess
调用泛型函数
助手类:
public IEnumerable<TReturn> Queries<TParent, TChild, TReturn>(string sql, Func<TParent, TChild, TReturn> map, string splitOn = "ID")
{
using (IDbConnection conn = new SqlConnection(ConfigurationManager.AppSettings["MyConnection"]))
{
conn.Open();
return conn.Query(sql, map, splitOn: splitOn);
}
}
你打电话是这样的:
string sql = "SELECT a.[Name], b.[MemberStatus] FROM [Member] a WITH (NOLOCK) INNER JOIN [MemberStatus] b WITH (NOLOCK) ON a.[ID] = b.[ID]";
return Helper.Queries<Member, MemberStatus, Member>(sql, (member, memberStatus) =>
{
member.MemberStatus = memberStatus;
return member;
});
这样,如果我还需要map,我只需要调用Helper.Queries,而不是重复打开连接,然后返回它。
这可能不是最好的答案,但这是我想出来的,它运作良好。
由于