C#C
C#3y ago
34 replies
kevin

✅ Issues with setting up different classes and sql connection

Could someone help me understand how I can setup this SQL connection? it's my first time organizing my code into different folders and really structuring my app with different folders, etc.

I get the error "A field initializer cannot reference the non-static field, method or property 'Customer.connection' ".

I want to make it so that I have a connection class that handles the connection. Currently I have: model class that talks to the dal class that talks to the connection class

I have the following class:

    public class Customer : ICustomer
    {
        private Connection connection;
        CustomerDAO db = new CustomerDAO(connection.CreateConnection());
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string Address { get; set; }

        // ctor
        public Customer(....)
        {
            .........
        }

        public void Create(Customer customer)
        {
            db.Create(customer)
        }


My connection class looks like this

    public class Connection
    {
        private string connectionString = "example string";

        public SqlConnection CreateConnection()
        {
            SqlConnection connection = new SqlConnection(connectionString);
            return connection;
        }
    }
Was this page helpful?