Search code examples
asp.net-mvcentity-frameworkobjectcontext

sharing objectcontext in entity Framework for an MVC application


I am developing an ASP.NET MVC application (Microsoft .NET Framework Version 3.5 SP1 using Entity Framework1.0). I have about 30 tables in my MySQL database. So far I have created 10 Model classes. I have an instance of the dataentity in all of my models.

Sample Model Class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyProj.Models
{
    public class SSDModel
private ddms_dataEntities2 db = new ddms_dataEntities2();

public ssd searchbyId(string id)
        {
            return db.ssd.FirstOrDefault(d => d.ssd_id_text == id);
        }

 public void add(ssd item)
        {
            db.AddTossd(item);
        }
}

When I try to access the method searchbyId() from another model class by instantiating an object of SSDModel, I was getting an exception - the objectcontext was not shared.

I am trying to find out the best way to share the object context between the model classes. I did go through SO and other sites for finding a solution. I understand the one of the best approaches would be to have one object context per HttpRequest. However, everything I found on the net is about entity-framework 4.0. I don't want to migrate the application to another version.

Please suggest a good document/blog/sample application that I can refer to. This is my first MVC application and any help would be greatly appreciated.

Thanks


Solution

  • You can pass the Context to the constructor when the SSDModel object created,

    public class SSDModel
           private ddms_dataEntities2 db;
    
           public SSDModel(ddms_dataEntities2  context){
              db=context;
           }
    
           public ssd searchbyId(string id)
            {
                return db.ssd.FirstOrDefault(d => d.ssd_id_text == id);
            }
    
            public void add(ssd item)
            {
                db.AddTossd(item);
            }
    }
    

    And when you are going to initialize sevaral model classes just create one context and pass that for all constructors.

    var ddms_dataEntities2 db = new ddms_dataEntities2();
    SSDModel ssd=new SSDModel(db);
    OtherModel other=OtherModel(db);
    

    One easy way to keep the context per request is describerd here
    Or else you can use IOC containers.