简体   繁体   English

MVC5 DataContext最佳实践?

[英]MVC5 DataContext Best Practice?

In MVC 5 there is a new Identity Class in the models folder. 在MVC 5中,models文件夹中有一个新的Identity Class。 SO let's say I add some additional fields to the user, I would do this in the class 所以我想说我向用户添加了一些额外的字段,我会在课堂上这样做

public class ApplicationUser : IdentityUser

Ok, so far so good. 好的,到目前为止一切顺利。 I run add-migration "updatedUser" and that will update the database. 我运行add-migration "updatedUser" ,这将更新数据库。

BUT... Now I want to add a Products, Client and Company Table. 但是......现在我要添加产品,客户和公司表。 Now, some ASP.NET tutorials and Azure tutorials have actually had me setting the getters and setters for each Table inside the ApplicationDbContext class: 现在,一些ASP.NET教程和Azure教程实际上让我为ApplicationDbContext类中的每个Table设置了getter和setter:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

        public DbSet<Product> Products { get; set; }
        public DbSet<Client> Clients { get; set; }
        public DbSet<Company> Companies { get; set; }

        public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

But I would think you would not want to inherit from that IdentityDbContext and instead set up a file inside the models folder called: 但我认为你不想从IdentityDbContext继承,而是在models文件夹中设置一个名为的文件:

DatabaseContext.cs (For non user/Identity tables) DatabaseContext.cs (对于非用户/身份表)

and do something like: 并做一些类似的事情:

    using MyProject.Domain.Entities;
    using System.Data.Entity;
    namespace MyProject.Models {

    public class DatabaseContext : DbContext 
        : base("DefaultConnection")
    {
    }

     public DbSet<Product> Products { get; set; }
     public DbSet<Client> Clients { get; set; }
     public DbSet<Company> Companies { get; set; }
}

Would this be best practice or should I use the Identity Class? 这是最佳做法还是应该使用Identity Class? Does it matter? 有关系吗?

Why would you think you would want to do that? 为什么你认为你会这样做?

You aren't inheriting anything you aren't already doing because of the ApplicationDbContext supplied. 由于提供了ApplicationDbContext,您不会继承您尚未执行的任何操作。

Adding a second context may make sense in some situations, but chances are you will want to access the Identity fields, and if you are using a different context then you can run into problems with context coherency. 在某些情况下添加第二个上下文可能有意义,但是您可能希望访问Identity字段,如果您使用的是其他上下文,则可能会遇到上下文一致性问题。

And, FYI, you don't put your DbSet's in the ApplicationDbContext's constructor. 而且,仅供参考,你不要将你的DbSet放在ApplicationDbContext的构造函数中。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM