You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Asp.Net Core 3.1多层MVC:如何将身份相关类移至数据层?

Hey there! Let's walk through how to move those scaffolded Identity classes from your main project to your data layer (Code First) step by step. I’ve done this setup a few times, so let’s break it down into manageable chunks:

1. Prep Your Data Layer Project

First off, make sure your data layer is a .NET Core 3.1 class library. Then, install the required NuGet packages if you haven’t already:

  • Microsoft.AspNetCore.Identity.EntityFrameworkCore (core Identity EF Core integration)
  • Microsoft.EntityFrameworkCore (base EF Core package)
  • Your preferred database provider (e.g., Microsoft.EntityFrameworkCore.SqlServer for SQL Server)

You can install these via the NuGet Package Manager, or run these commands in the Package Manager Console (PMC):

Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore -Version 3.1.32
Install-Package Microsoft.EntityFrameworkCore -Version 3.1.32
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.1.32
2. Migrate Identity Entity Classes

Head over to your main project’s Identity/Data folder (where the scaffolded Identity files live). Copy over any custom Identity entities you have—most likely ApplicationUser (if you extended the default IdentityUser), plus any custom roles, user roles, or claims classes you scaffolded.

  • Paste these classes into your data layer project (I usually put them in a Models or Identity subfolder for organization).
  • Update the namespace of these classes to match your data layer’s namespace (e.g., change YourMainApp.Identity.Data to YourDataLayer.Models).
3. Move the ApplicationDbContext to Data Layer

Next, find the ApplicationDbContext class in your main project’s Identity folder. Copy this file to your data layer project:

  • Update its namespace to match the data layer.
  • Double-check that it inherits from the correct Identity DbContext type. If you’re using a custom ApplicationUser, it should look like this:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using YourDataLayer.Models;

namespace YourDataLayer.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        // Keep any custom DbSets or OnModelCreating configurations you added during scaffolding
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Add your custom table mappings or seed data here if you have any
        }
    }
}
4. Update Main Project Dependencies & Configuration

Now we need to clean up the main project and point it to the data layer’s Identity components:

  • Delete the original ApplicationDbContext and Identity entity classes from your main project (or the entire Identity/Data folder if you don’t have other files there).
  • Add a project reference from your main project to the data layer project (right-click main project → Add → Project Reference → select your data layer).
  • Update Startup.cs in your main project:
    • In ConfigureServices(), update the DbContext registration to use the data layer’s ApplicationDbContext:
      services.AddDbContext<ApplicationDbContext>(options =>
          options.UseSqlServer(
              Configuration.GetConnectionString("DefaultConnection")));
      
    • Update the Identity registration to reference the data layer’s ApplicationUser and ApplicationDbContext:
      services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
          .AddEntityFrameworkStores<ApplicationDbContext>();
      
  • Update your main project’s _ViewImports.cshtml to reference the data layer’s namespace instead of the old Identity namespace:
    @using YourDataLayer.Models
    
5. Fix Identity Razor Page References

The Identity Razor Pages (login, register, etc.) stay in your main project’s Identity folder—they’re part of the UI layer. But you need to update their code-behind files to use the data layer’s entities:

  • Open each .cshtml.cs file (like Login.cshtml.cs, Register.cshtml.cs) and update the using statements to point to your data layer’s namespace instead of the old main project Identity namespace.
  • For example, change using YourMainApp.Identity.Data; to using YourDataLayer.Models;.
6. Run Code First Migrations

Now let’s sync the database with our new data layer setup:

  • Open the Package Manager Console, and set your data layer project as the Default Project (use the dropdown at the top of PMC).
  • Run this command to create a new migration:
    Add-Migration IdentityMovedToDataLayer
    
  • Then apply the migration to your database:
    Update-Database
    
    Note: If you already had Identity migrations in the main project, make sure the migration history is consistent. If this is a fresh setup, this will create all the standard Identity tables in your database.
7. Test Everything Out

Finally, fire up your main project and test all Identity flows: register a new user, log in, reset a password, etc. If you hit compile errors, it’s almost always a missing or incorrect namespace reference—double-check your using statements across all files.

内容的提问来源于stack exchange,提问作者n.e

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 08:12:47