Passing around a SqlConnection

前端 未结 4 1434
花落未央
花落未央 2021-01-25 13:09

I have created a TransactionScope and within the scope various items are created and updated in the database. During this process I make a lot of calls to the database. Original

4条回答
  •  感情败类
    2021-01-25 13:35

    I tend to avoid passing connections around at all cost. I've just seen too many errors creep into a system when someone else, for example, closes a connection in the middle of a sequence of operations because they didn't know others were going to use the same connection.

    Creating a SQLConnection is almost free due to ADO.NET's connection pooling mechanisms so don't think you're going to save any space/time by creating one and passing it around.

    If, as in your situation, you truly do need to perform a number of DB operations within a transaction scope, then manage your scope appropriately, but create, use and dispose of your connections as and when you need them - it'll help keep your code A LOT cleaner and safer.

提交回复
热议问题