Converting using SqlConnection to Func delegate

旧时模样 提交于 2019-12-25 05:34:15

问题


I have the following code that is being copied and pasted in a number of places. The only difference being that there is a single call in the middle of the usings which changes. So I made a

public MyEntity Read(int id)
{
    using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
    {
        sqlConn.Open();
        return MyDataLayer.Select(sqlConn, id);
    }
}

So I came up with this. However, my problem is how do i pass the sqlConn var to the call?

public TResult UsingSqlConnection<TResult>(Func<TResult> myFunction)
{
    using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
    {
        sqlConn.Open();
        return myFunction();
    }
}

public MyEntity Read(int id)
{
    return UsingSqlConnection(() => MyDataLayer.Read(id)); 
   //PROBLEM: Read() requires sqlConn
}

Off the top of my head - it looks like instead of passing it as a param, that I need to create a property for SqlConn in MyDataLayer and assign it in the UsingSqlConnection method using an interface. While i wont rule out that refactor, I am wondering if I am missing something as this is my first attempt with Func delegates in this way.


回答1:


Func can have parameters:

public TResult UsingSqlConnection<TResult>(Func<SqlConnection, TResult> myFunc)
{
    using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
    {
        sqlConn.Open();
        return myFunc(sqlConn);
    }
}

public MyEntity Read(int id)
{
    return UsingSqlConnection((sqlConn) => MyDataLayer.Read(sqlConn, id));       
}


来源:https://stackoverflow.com/questions/9253158/converting-using-sqlconnection-to-func-delegate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!