自定义身份模型后ASP MVC 5更新数据库引发实体验证错误

本文关键字:数据库 实体 错误 验证 更新 模型 身份 ASP MVC 自定义 | 更新日期: 2023-09-27 17:59:41

我更新了我的身份模型,如下所示,因为我需要扩展IdentityUserRole类,以便可以向其添加其他属性:

 public class ApplicationUserLogin : IdentityUserLogin { }
 public class ApplicationUserClaim : IdentityUserClaim { }
 public class ApplicationUserRole : IdentityUserRole
 {
    public ApplicationUserRole()
    : base()
    { }
    public virtual ApplicationRole Role { get; set; }
 }  
 public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
 {
    public ApplicationRole() : base() { }
    public ApplicationRole(string name) : this()
    {
        this.Name = name;
    }
    public virtual ICollection<Permission> Permissions { get; set; }
}
public class ApplicationUser : IdentityUser<string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool HasPermission(string permission)
    {
        return Roles.Any(r => r.Role.Permissions
                  .Any(p => p.Name == permission));
    }
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

为了适应上述变化,我创建了一个新的应用程序用户库,如下所示:

public class ApplicationUserStore : UserStore<ApplicationUser, ApplicationRole, string, 
    ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public ApplicationUserStore(ApplicationDbContext context)
        : base(context)
    {
    }
} 

并更新了identity.config文件,以便用户管理器使用新的用户存储:

public class ApplicationUserManager : UserManager<ApplicationUser, string> 
{ 
    public ApplicationUserManager(IUserStore<ApplicationUser, string> store) 
        : base(store) 
    { 
    } 
    public static ApplicationUserManager Create(
        IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)  
    { 
        var manager = new ApplicationUserManager(
            new ApplicationUserStore(context.Get<ApplicationDbContext>())); 
        ...
    }
}

在我的种子方法中,我有以下内容:

 var userManager = new ApplicationUserManager(new ApplicationUserStore(context));
 var user = new ApplicationUser();
 user.UserName = "joe.blogs@domain.com";
 user.Email = "joe.blogs@domain.com";
 user.FirstName = "Joe";
 user.LastName = "Blogs";
 string userPWD = "Abcde_1";
 userManager.Create(user, userPWD);

当我运行更新数据库命令时,我得到以下错误:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

将错误写入显示的文本文件:

Entity of type "ApplicationUser" in state "Added" has the following validation errors: 
- Property: "Id", Error: "The Id field is required."

为什么我需要提供一个Id字段——因为我仍然使用字符串作为主键,所以它不是应该自动生成的吗?我的用户表与以前没有什么不同:

CreateTable(
            "dbo.User",
            c => new
                {
                    Id = c.String(nullable: false, maxLength: 128),
                    FirstName = c.String(nullable: false, maxLength: 255),
                    LastName = c.String(nullable: false, maxLength: 255),
                    Email = c.String(maxLength: 256),
                    EmailConfirmed = c.Boolean(nullable: false),
                    PasswordHash = c.String(),
                    SecurityStamp = c.String(),
                    PhoneNumber = c.String(),
                    PhoneNumberConfirmed = c.Boolean(nullable: false),
                    TwoFactorEnabled = c.Boolean(nullable: false),
                    LockoutEndDateUtc = c.DateTime(),
                    LockoutEnabled = c.Boolean(nullable: false),
                    AccessFailedCount = c.Int(nullable: false),
                    UserName = c.String(nullable: false, maxLength: 256),
                })
            .PrimaryKey(t => t.Id)
            .Index(t => t.UserName, unique: true, name: "UserNameIndex");

自定义身份模型后ASP MVC 5更新数据库引发实体验证错误

我不得不将以下内容添加到ApplicationUser类中以修复:public ApplicationUser(){this.Id=Guid.NewGuid().ToString();}。因此,如果您希望扩展这些身份模型中的任何一个,但希望保留默认的字符串主键,那么您似乎必须在扩展的每个类中重新实现它的重新生成