C#的DbConnection转换为的SqlConnection [英] C# DbConnection cast to SqlConnection

查看:2164
本文介绍了C#的DbConnection转换为的SqlConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这段代码在一个应用程序

I found this piece of code in one application

Database database = DatabaseFactory.CreateDatabase("connection string");
DbConnection connection = database.CreateConnection();
connection.Open();
SqlConnection sqlConnection = (SqlConnection)connection;



它是安全的,SqlConnection的自DbConnection derieve。数据库来源于Microsoft.P​​ractices.EnterpriseLibrary.Data。根据文档CreteDatabase返回的DbConnection。

Is it safe, SqlConnection derieve from DbConnection. Database comes from Microsoft.Practices.EnterpriseLibrary.Data. According to documentation CreteDatabase returns DbConnection.

推荐答案

没有它是不是安全,铸造是永远安全,您的应用程序运行时,可能随时打击。而的SqlConnection 的DbConnection 确实派生你不能保证 database.CreateConnection()将返回的SqlConnection ,因为这可以在配置文件中的参数进行调整。也就是为什么你需要转换为的SqlConnection ?它始终是更好地与那些在更高的层次,以避免与具体实施,这将使你的代码不可能孤立地测试你的连接代码类的工作。

No it is not safe, casting is never safe and it may blow anytime while your application is running. While SqlConnection derives indeed from DbConnection you are not guaranteed that database.CreateConnection() will return a SqlConnection as this could be parametrized in the configuration file. Also why do you need to cast to SqlConnection? It is always better to work with classes that are higher in the hierarchy to avoid coupling your code with a specific implementation which will make your code impossible to test in isolation.

虽然EnterpriseLibrary确实在保持抽象的东西,你用这个转换杀一切体面的好工作。你还应该确保可支配资源总是妥善处理。这个怎么样,而不是:

While the EnterpriseLibrary does a decently good job in keeping things abstract you are killing everything with this cast. Also you should make sure that disposable resources are always disposed properly. How about this instead:

Database database = DatabaseFactory.CreateDatabase("connection string");
using (var conn = database.CreateConnection())
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT id FROM foo";
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            // TODO: work with the results here
        }
    }
}

这样,你的代码是少脆弱,在配置文件数据库更改。嗯,当然,你仍然有这个SQL硬编码并且有将这种情况护理奥姆斯。他们也将让你专注于你的应用程序,而不是编写SQL查询,并从一个数据库提供商转换为另一种浪费时间的真实域名。但是,对于一个简单的应用程序,这是确定。

This way your code is less fragile to database changes in the config file. Well of course you still have this SQL hardcoded and there are ORMs that will take care of this situation. They will also allow you to focus on the real domain of your application instead of wasting time in writing SQL queries and casting from one database provider to another. But for a simple application this is OK.

这篇关于C#的DbConnection转换为的SqlConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆