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

C# MVC5三层应用迁移IdentityModels至DataAccessLayer遇错误求助

Hey Amir, let’s work through those user.G-related errors you’re facing after moving your Identity models to a class library. I’ve dealt with similar issues when restructuring Identity into separate layers, so here’s a step-by-step breakdown of what to check and fix:

1. Verify Namespace References

First, make sure all the files throwing errors (IdentityConfig.cs, Startup.Auth.cs, and your Manage controller) have the correct namespace reference for your class library’s models. Add this at the top of each file if it’s missing:

using YourClassLibraryNamespace.Models; // Replace with your actual class library namespace

This ensures the code is referencing your migrated ApplicationUser class instead of a leftover version in the web project.

2. Check Your Class Library’s ApplicationUser Definition

Double-check that your class library’s ApplicationUser class is properly set up to include all the properties and methods your code is trying to access (like the user.Gxxxx properties/methods):

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Security.Claims;
using System.Threading.Tasks;

namespace YourClassLibraryNamespace.Models
{
    public class ApplicationUser : IdentityUser
    {
        // Add your custom G-prefixed property (e.g., Gender, GenerateUserIdentityAsync, etc.)
        public string Gender { get; set; }

        // Ensure this method exists if your code uses it (common in IdentityConfig/Startup.Auth)
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add any custom claims here if needed
            return userIdentity;
        }
    }
}

If you had custom properties or methods starting with G in your original ApplicationUser, they must exist in this class library version.

3. Update IdentityConfig.cs to Use the Class Library Models

In the ApplicationUserManager.Create method, confirm that the UserStore and ApplicationUserManager are using your class library’s ApplicationUser and ApplicationDbContext:

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
    // Use your class library's DbContext here
    var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
    
    // Rest of your UserManager configuration (validation, password settings, etc.)
    return manager;
}

Ensure ApplicationDbContext in your class library inherits from IdentityDbContext<ApplicationUser>:

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

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

4. Correct Startup.Auth.cs Configuration

In ConfigureAuth(IAppBuilder app), make sure the SecurityStampValidator.OnValidateIdentity uses your class library’s ApplicationUserManager and ApplicationUser:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

If the GenerateUserIdentityAsync method is missing from your class library’s ApplicationUser, this will throw an error referencing user.G... (since the method call starts with user.Generate...).

5. Fix Manage Controller Code

In your Manage controller, confirm that the UserManager is typed to your class library’s ApplicationUser, and that any calls to user.Gxxxx are accessing valid properties/methods from that class:

// At the top of the controller
using YourClassLibraryNamespace.Models;
using Microsoft.AspNet.Identity;

// In your action method
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
// Access your custom property, e.g.:
ViewBag.Gender = user.Gender;

If user is still typed to the old web project’s ApplicationUser, it won’t recognize the migrated properties.

6. Clean and Rebuild Your Solution

Sometimes residual build cache can cause false errors. Run these steps:

  • Go to Build > Clean Solution to clear old compiled files
  • Then go to Build > Rebuild Solution to compile all projects from scratch

This ensures all references are properly resolved and the latest version of your class library is used.

内容的提问来源于stack exchange,提问作者Amir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:20:32