简体   繁体   English

ASP MVC 实体框架数据库上下文和类

[英]ASP MVC Entity Framework Database context and classes

In my asp mvc Framework project, using EF, I have some objects (from classes) whose fields store data coming from my database.在我的 asp mvc 框架项目中,使用 EF,我有一些对象(来自类),其字段存储来自我的数据库的数据。

My question is:我的问题是:

How to populate these fields, or manage methods of these objects using a dbcontext variable?如何使用 dbcontext 变量填充这些字段或管理这些对象的方法?

Sol 1: Is it better to use each time I need a connection with db in my classes with the instruction (using (resource), see below )?解决方案 1:每次我需要在我的课程中使用指令与 db 建立连接时使用会更好吗(使用(资源),见下文)?

Sol 2: Is it betterI to code a singleton class to use one instance of the context?解决方案 2:使用上下文的一个实例编写 singleton class 是否更好?

Sol 3: Or should I use another way for the links beetween my classes and the database? Sol 3:或者我应该对我的课程和数据库之间的链接使用另一种方式?

What is the best method considering performances and code quality.考虑性能和代码质量的最佳方法是什么。

Thanks for your attention.感谢您的关注。

Solution 1解决方案 1

 public class Test
    {
        private  T1 a;
        private  T2 b;
       
        public Test()
        
        {}

        public void CreateFrom (int id) 
        
        {
            using (var db=new WebApplicationMVCTest.Models.dbCtx())
            {
                a=db.T1s.Find(id);
                b= db.T2s.Find(a.id2);
                
            }
        }

Solution 2:解决方案2:

public class DbSingleton
    {

        private static dbCtx instance;

        private int foo;

        private DbSingleton ()
            {}

        public static dbCtx Current
        {
            get
            {
                if (instance == null) 
                {
                    instance = new dbCtx();
                }
                return instance;
            }
        }


        public static void Set (dbCtx x)
        {

            if (instance==null)
            {
                instance = x;
            }
           

        }
 
    }

For a web project, never use a static DbContext.对于 web 项目,切勿使用 static DbContext。 EF DbContexts are not thread safe so handling multiple requests will lead to exceptions. EF DbContexts 不是线程安全的,因此处理多个请求将导致异常。

A DbContext's lifespan should only be as long as it is needed. DbContext 的生命周期应该只在需要的时候。 Outside of the first time setup cost when a DbContext is used for the first time, instantiating DbContexts is fast.除了第一次使用 DbContext 时的首次设置成本之外,实例化 DbContexts 很快。

My advice is to start simple:我的建议是从简单开始:

public ActionResult Create(/* details */)
{
    using (var context = new AppDbContext())
    {
         // do stuff.
    }
}

When you progress to a point where you learn about, and want to start implementing dependency injection applications then the DbContext can be injected into your controller / service constructors.当您了解并想要开始实施依赖注入应用程序时,可以将 DbContext 注入到您的 controller / 服务构造函数中。 Again, from the IoC container managing the DbContext, the lifetime scope of the Context should be set to PerWebRequest or equivalent.同样,从管理 DbContext 的 IoC 容器中,应将 Context 的生存期 scope 设置为 PerWebRequest 或等效项。

private readonly AppDbContext _context;

public MyController(AppDbContext context)
{
    _context = context ?? throw new ArgumentNullException("context");
}

public ActionResult Create(/* details */)
{
    // do stuff with _context.
}

The gold standard for enabling unit testing would be injecting a Unit of Work pattern and considering something like the Repository pattern to make your dependencies easier to unit test.启用单元测试的黄金标准是注入一个工作单元模式并考虑像存储库模式这样的东西,以使您的依赖项更容易进行单元测试。

The best advice I can give you starting out with EF and MVC is to avoid the temptation to pass Entities between the controller (server) and the UI.从 EF 和 MVC 开始,我能给你的最好建议是避免在 controller(服务器)和 UI 之间传递实体的诱惑。 (views) You will come across dozens of examples doing just this, but it is a poor choice for performance, it also hides a LOT of land mines and booby traps for both performance, exceptions, and data security issues. (views) 你会遇到几十个这样做的例子,但它在性能方面是一个糟糕的选择,它还隐藏了很多性能、异常和数据安全问题的地雷和陷阱。 The most important detail is that when the UI calls the controller passing what you expect will be an entity, you are not actually getting an entity, but a de-serialized JSON object cast to an entity.最重要的细节是,当 UI 调用 controller 传递您期望的实体时,您实际上并没有获得实体,而是将反序列化的 JSON ZA8CFDE6331BD59EB2AC96F8911C4B66Z 转换为实体。 It is not an entity that is tracked by the DbContext handling the request.它不是由处理请求的 DbContext 跟踪的实体。 Instead, get accustomed to passing view models (serializable data containers with the data the view needs or can provide) and IDs + values where the controller will re-load entities to update the data only as needed.相反,习惯于传递视图模型(具有视图需要或可以提供的数据的可序列化数据容器)和 ID + 值,controller 将重新加载实体以仅在需要时更新数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架 ASP.NET MVC 5 中事务中的存储过程和数据库上下文操作 - Stored Procedure and Database Context Operation in a Transaction in Entity Framework ASP.NET MVC 5 实体框架不会从 MVC 中的实体数据模型(来自现有数据库)创建上下文和表类(.cs) - Entity Framework doesn't create Context and table classes(.cs) from Entity Data Model (from existing database) in MVC ASP.NET MVC5实体框架应用程序中的单个上下文 - Single Context in ASP.NET MVC5 Entity Framework application 在 LINQ Entity Framework asp.net MVC 5 中切换数据库上下文 - Switching DB Context in LINQ Entity Framework asp.net MVC 5 PopUp 不在 ASP.NET MVC 5 和实体框架中的数据库中发送数据 - PopUp not sending data in database in ASP.NET MVC 5 and Entity Framework ASP.net MVC与Entity Framework重新排序数据库记录 - ASP.net MVC with Entity Framework reordering database records ASP.NET MVC 4实体框架数据库第一个存储库 - ASP.NET MVC 4 Entity Framework Database First Repository 使用 asp.net mvc 4 + Entity Framework 将图像保存到数据库 - Saving images to database with asp.net mvc 4 + Entity Framework 配方-Entity Framework ASP.NET MVC中的成分数据库 - Recipe - ingredients database in Entity Framework ASP.NET MVC Entity Framework Core 和 ASP.NET Core MVC 中的 Inheritance 数据库 - Inheritance Database in Entity Framework Core and ASP.NET Core MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM