在c#全局连接中要在所有类中使用 [英] in c# global connection to be used in all classes
问题描述
我已经将一个连接字符串保存到 Properties.Settings.Default
中,我需要在所有类中使用sql连接,而不必每次都声明它,那么该如何声明呢?>
I've a connection string saved to Properties.Settings.Default
, i need to use an sql connection in all classes without having to declare it everytime, so how should it be declared?
推荐答案
实际上,您不需要在任何地方都使用单个 SqlConnection
.更好的方法是创建一个类来管理您的数据访问.通常,这是数据访问层(DAL)的职责.DAL是处理所有与数据库相关的东西的一组类.
You actually don't need to use a single SqlConnection
everywhere. A better approach would be to create a class to manage you data access. Typically this is the duty of your Data Access Layer (DAL). DAL is a set of classes that handle all the database related stuff.
为此目的一个非常简单的类可能是这样的:
A very simple class for this purpose could be something like this:
public class DatabaseManager
{
private static DatabaseManager _instance;
private DatabaseManager()
{
}
static DatabaseManager()
{
_instance = new DatabaseManager();
}
public DatabaseManager Instance
{
get { return _instance; }
}
private string GetConnectionString()
{
return Properties.Settings.Default.MyConnectionString;
}
public SqlConnection CreateConnection()
{
return new SqlConnection(GetConnectionString());
}
}
您可以扩展此类,以包含其他方法来执行查询.
You can extend this class to contain another methods to execute your queries.
我强烈建议您使用 ORM(对象关系映射器),例如<一个href ="http://msdn.microsoft.com/en-us/data/ef.aspx" rel ="nofollow">实体框架.
I highly recommend you to use an ORM (Object-Relational Mapper) like Entity Framework.
这篇关于在c#全局连接中要在所有类中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!