in c# global connection to be used in all classes

后端 未结 5 1866
萌比男神i
萌比男神i 2021-01-22 18:59

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

5条回答
  •  [愿得一人]
    2021-01-22 19:28

    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.

    I highly recommend you to use an ORM (Object-Relational Mapper) like Entity Framework.

提交回复
热议问题