Sharing an objectcontext in a Framework entity for an MVC application

I am developing an ASP.NET MVC application (Microsoft.NET Framework version 3.5 Service Pack 1 (SP1) using Entity Framework1.0). I have about 30 tables in my MySQL database. So far I have created 10 model classes. I have a data instance on all my models.

Model Example:

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 searchbyId () method from another model class by creating an instance of the SSDModel object, I get an exception - the contexttext object was not split.

I am trying to find a better way to share an object context between model classes. I went through SO and other sites to find a solution. I understand that one of the best approaches would be to have a single object context for HttpRequest. However, all that I found on the network is the entity framework 4.0. I do not want to port the application to another version.

Please offer 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

+4
source share
1 answer

You can pass Context to the constructor when creating the SSDModel object,

 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 the model north classes, just create one context and pass it to all the constructors.

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

One easy way to maintain context for each request is described here.
Or you can use IOC containers .

+2
source

Source: https://habr.com/ru/post/1445666/


All Articles