Skip to main content
 首页 » 编程设计

c#之在 MVC 中使用 DBCONTEXT 类的正确方法

2024年02月13日14langtianya

在 MVC 中,我们创建像这样的 Dbcontext 模型

 public class Model1 : DbContext 
    { 
        public Model1() 
            : base("DefaultConnection") 
        {} 
        public DbSet<SomeObj> SomeObjSet { get; set; } 
    } 
 
//another model 
 
 public class Model2 : DbContext 
        { 
            public Model2() 
                : base("DefaultConnection") 
            {} 
            public DbSet<SomeObj2> SomeObjSet { get; set; } 
        } 

然后我们使用像这样的 Controller

public class SomeController : Controller 
    { 
        private Model1 db1 = new Model1(); 
        private Model2 db2 = new Model2(); 
 
        public ActionResult Action1() 
        { 
            //do sth with Model1 and return 
            return View(db1.SomeObjSet.ToList());//  
        } 
 
         public ActionResult Action2() 
        { 
            //do sth with Model2 and return result 
            return View(db2.SomeObjSet.ToList());//  
        } 

但我的问题是,通过这种方式我们创建了多个 DBConnections。将两个模型合并为一个模型并为每个 Controller 配备一个专用模型是否更好?

请您参考如下方法:

But my question is that isn't that in this way we are creating Multiple DBConnections.

不,不用担心。 Entity Framework (或更具体地说,它所依赖的 ADO.NET)处理连接池中的实际数据库连接。所以不要将 DbContext 与实际的 DbConnection 混淆。这是两个完全不同的东西。