Asp.Net Core:向 IdentityDbContext 添加数据或使用 DbContext

Asp.Net Core: Add data to IdentityDbContext or use DbContext(Asp.Net Core:向 IdentityDbContext 添加数据或使用 DbContext)
本文介绍了Asp.Net Core:向 IdentityDbContext 添加数据或使用 DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Asp.Net Core WebApi 项目.

我可以将我的表添加到 IdentityDbContext,如下所示:

Can I add my tables to IdentityDbContext, like this:

public class ApplicationDbContext : IdentityDbContext<User>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        { }

        public DbSet<ProgrammerRole> ProgrammerRoles { get; set; }

        public DbSet<Project> Projects { get; set; }
        public DbSet<SubProject> SubProjects { get; set; }

        public DbSet<Report> Reports { get; set; }
    }

或者我是否需要创建第二个 DbContext.如果我创建第二个 DbContext我如何在 IdentityDbContext 中与用户交流.

Or do I need to create a second DbContext. And if i create a second DbContext how can I communicate wiht User in IdentityDbContext.

我的第二个问题:如果我在 IdentityDbContext 中添加数据,如上所示,如何从 ApplicationDbContext 中的表中获取数据?因为每次创建 ApplicationDbContext 的新实例时,我都需要传递 DbContextOptions 对象.我在 Startup.cs 中执行此操作:

And my second question: If i add data in IdentityDbContext, like above, How do I get the data from my tables in ApplicationDbContext? Because i need to pass DbContextOptions object every time I create a new instance оf ApplicationDbContext. I do this in Startup.cs:

// ===== Add DbContext ========
            var connectionString = Configuration.GetConnectionString("DbConnection");
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(connectionString));

我在旧版本的 Asp.Net Core 中看到,我可以在 IdentityDbContext 构造函数中传递连接字符串,但现在只能传递 DbContextOptions.而我做不到,例如这个:

I saw in older version of Asp.Net Core, that i can pass Connection String in IdentityDbContext constructor, but now only DbContextOptions. And i can't do, for example this:

[AllowAnonymous]
        [HttpGet]
        public IEnumerable<Project> GetRoles()
        {
            using (var db = new ApplicationDbContext())
            {
                return db.Projects;
            }
        }

推荐答案

我可以像这样将我的表添加到 IdentityDbContext 中吗:

Can I add my tables to IdentityDbContext, like this:

是的,这就是您创建自定义表格的方式.您不需要创建另一个 DbContext.例如

Yes, it is how you create custom tables. You do not need to create another DbContext. E.g.

public class Project
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Project> Projects { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Project>(entity =>
        {
            entity.Property(e => e.Name)
                .IsRequired()
                .HasMaxLength(50);
        });

        base.OnModelCreating(builder);
    }
}

注意:您可能需要运行 dotnet ef migrations add Initialdotnet ef database update 进行数据库迁移.

Note: you might need to run dotnet ef migrations add Initial and dotnet ef database update for database migration.

使用 (var db = new ApplicationDbContext()) {...}

using (var db = new ApplicationDbContext()) {...}

不应该在控制器内部创建或管理 ApplicationDbContext.如果这样做,它们就会变得紧密耦合,并且您无法实现单元测试.

You should not create or manage ApplicationDbContext inside controller. If you do so, they become tightly coupled, and you cannot implement unit tests.

相反,您让依赖反转 (DI) 容器为您管理它.例如.

Instead, you let dependency inversion (DI) container manage it for you. E.g.

public class UserController : Controller
{
    private readonly ApplicationDbContext _context;

    public UserController(ApplicationDbContext context)
    {
        _context = context;
    }

    [AllowAnonymous]
    [HttpGet]
    public IEnumerable<Project> GetRoles()
    {
        return _context.Projects;
    }
}

这篇关于Asp.Net Core:向 IdentityDbContext 添加数据或使用 DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)
Bind multiple parameters from route and body to a model in ASP.NET Core(在ASP.NET Core中将路由和主体中的多个参数绑定到一个模型)
Custom model binding in AspNet Core WebApi?(AspNet Core WebApi中的自定义模型绑定?)
How to minify in .net core mvc view?(如何在.Net核心MVC视图中缩小?)