如何在 mvc 标识项目中创建数据库上下文对象 asp.net



我使用此命令创建了一个新的 ASP.NET 项目

dotnet new mvc --auth Individual

它仅生成注册和登录操作。我还需要为产品模型创建、读取、更新和删除操作。但是我无法创建 DatabaseContext 实例。我尝试创建这样的对象:

private ApplicationDbContext ctx = new ApplicationDbContext();

它说一个错误:

没有给出与所需的形式相对应的参数 参数"选项"的 'ApplicationDbContext.ApplicationDbContext(DbContextOptions(' [项目名称]

这是 ApplicationDbContext.cs 文件:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }
    }

那么如何创建 ApplicationDbContext 类的对象呢?

问题是关于创建ApplicationDbContextobject。可以在MVC项目的IdentityModels.cs文件中找到ApplicationDbContext类。

Models文件夹中类的自动命名空间为YourProjectName.Models

至于options你可以在这里阅读:

调用新的 DbContext 时,DbContextOptions 中会包含哪些内容?

给定连接字符串名称为 DefaultConnection ,它可能是这样的:

var options = new DbContextOptionsBuilder<ApplicationDbContext>();
options.UseSqlServer(Configuration.GetConnectionStringSecureValue("DefaultConnection"));

因此,要在代码中生成ApplicationDbContext对象,只需使用自动生成的命名空间并生成选项来初始化对象,如下所示:

using YourProjectName.Models; //initialize your .cs file with this
...
var options = new DbContextOptionsBuilder<ApplicationDbContext>();
options.UseSqlServer(Configuration.GetConnectionStringSecureValue("DefaultConnection"));
ApplicationDbContext context = new ApplicationDbContext(options); //somewhere else in the file

然后像这样使用它:context.Users...context.YourOtherTableNames.EFMethod...

最新更新