Passing in same SqlConnection to >1 method in same class
I have a class which focuses on database operations (e.g. write/read etc). Is there an elegant way to pa开发者_JAVA百科ss in the same SqlConnection to each methoid as opposed to making a new object as a local variable in each parameter?
I remember seeing an example of this, on this site, using a lambda expression. That was ideal but can't find it.
Thanks
IMHO, it is an absolutely bad idea to pass a SqlConnection object between classes.
It is much much better to simply create a new connection object just before usage. In other words, within each method that makes a database call. SqlConnection is an IDisposable class that deals with unmanaged resources. If something get's hosed then you run the possibility of leaking connections.
Also, creating and disposing of those connection objects is an extremely fast operation due to connection pooling that is handled at a much lower layer than your code. Which means the only benefit you get by passing it in is 1 less line of code per method that performs data access; while the downside is a potential inability to perform any additional sql calls without shutting down your application. If this is a web app, then this it's a completely horrible decision as it would potentially shut down the entire site.
That said, passing the connection string around is okay, although this is something that typically is loaded through your config file.
you can also use optional parameters and if no connection is passed in and the parameter value is null, then you create one otherwise you simply use the one passed.
精彩评论