Question

I open Database connection in my controller and pass the opened connection to my Model for using that connection.

but since 2nd time calling to the controller(Ajax), it return an error message that say 'Connection must be open.' I reloaded page, and call the controller again then it works well. but for the 2nd time calling, it keep return that error message.

My controller has the code to open DB Connection, so I believed, it should open database for every processing(Calling). and the (open) code is in using{} block so after using it, it should be closed automatically.

but I think I'm doing wrong :(

here is my code,

public JsonResult myControllerMethod() // Action Controller
{
    using (AdsConnection conn = new AdsConnection(connString))
    {
    conn.Open();
    AdsTransaction txn = conn.BeginTransaction(); // Begin Transaction
    try
    {
        MyModel mo = new MyModel();
        mo.doProcess(conn); // pass connection to model
        txn.Commit();
        return Json(new { success = true });
    }
    catch (Exception e)
    {
        txn.Rollback();
        return Json(new { success = false, message = e.Message });
    }
    }
}

MyModel

public void doProcess(AdsConncection conn){ // Model
    try{
        ..
        //AdsCommand select, update, delete and insert....
        ..
    }catch(Exception e){
        throw e;
    }
}

Anybody know, what I am doing wrong? please advice me.

Thanks

Was it helpful?

Solution

You shouldn't pass a database connection to your view - your view should accept an object (as a model) that contains "solid" data. A view should have no logic of its own, and a Model's logic should only be concerned with modifying internal state, such as performing validation (not verification) or some internal data transformation. The task of populating a Model from a database should be done by the controller or a separate mapping class (or by some kind of "Populate" method of the model, but this method should be called and contained within the controller's action method).

That said, the problem you're experiencing is because you're using using() blocks. A using() block will always call the IDisposable.Dispose() method of its subject object, in this case a DB connection. SqlConnection.Dispose calls its .Close method, which is why the connection object is closed whenever the method returns.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top