【问题标题】:Asp.Net Core: Add data to IdentityDbContext or use DbContextAsp.Net Core:向 IdentityDbContext 添加数据或使用 DbContext
【发布时间】:2018-10-26 21:51:43
【问题描述】:

我使用 Asp.Net Core WebApi 项目。

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

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 中与用户交流。

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

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

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

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

【问题讨论】:

    标签: asp.net asp.net-core entity-framework-6 asp.net-identity entity-framework-core


    【解决方案1】:

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

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

    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 进行数据库迁移。

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

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

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

    public class UserController : Controller
    {
        private readonly ApplicationDbContext _context;
    
        public UserController(ApplicationDbContext context)
        {
            _context = context;
        }
    
        [AllowAnonymous]
        [HttpGet]
        public IEnumerable<Project> GetRoles()
        {
            return _context.Projects;
        }
    }
    

    【讨论】:

      【解决方案2】:

      我解决了我的问题,我只是替换了我的 ApplicationDbContext 中的代码,并从方法中获取连接字符串:

      public class ApplicationDbContext : IdentityDbContext<User>
          {
              protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
              {
                  optionsBuilder.UseSqlServer(GetConnectionString());
              }
      
              private static string GetConnectionString()
              {
                  const string databaseName = "EmployeeReportsDb";
                  const string databasePass = "SuperPuper_Random_DB-key!";
      
                  return $"Server=localhost;" +
                         $"database={databaseName};" +
                         $"Trusted_Connection = True;" +
                         $"MultipleActiveResultSets = True;" +
                         $"pwd={databasePass};" +
                         $"pooling=true;";
              }
      
              public DbSet<ProgrammerRole> ProgrammerRoles { get; set; }
      
              public DbSet<Project> Projects { get; set; }
              public DbSet<SubProject> SubProjects { get; set; }
      
              public DbSet<Report> Reports { get; set; }
          }
      

      这里是资源:https://medium.com/@ozgurgul/asp-net-core-2-0-webapi-jwt-authentication-with-identity-mysql-3698eeba6ff8

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-27
        • 2018-03-24
        • 2018-08-24
        • 2015-01-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多