Asp.net核心标识“INSERT语句与FOREIGN KEY约束冲突”

时间:2016-12-22 09:57:26

标签: c# asp.net-mvc asp.net-identity entity-framework-core seeding

我使用ASP.NET CORE Identity创建ASP.NET CORE应用程序。 我创建了种子类,用于为第一个启动应用程序保存新用户和角色。在这个种子类中,当我向用户添加角色时,我会收到以下错误。

  

INSERT语句与FOREIGN KEY约束冲突   “FK_AspNetUserRoles_AspNetUsers_UserId”。冲突发生在   数据库“DB_A14695_Elvinm”,表“dbo.AspNetUsers”,列“Id”。该   声明已被终止。

我使用以下类来识别身份

public class ApplicationUser : IdentityUser
{
    public int Type { get; set; }
    public int Flags { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime LastModifiedDate { get; set; }
}

我的种子班

 public class DbSeeder
{
    #region Private Members
    private RvMusicalDbContext DbContext;
    private RoleManager<IdentityRole> RoleManager;
    private UserManager<ApplicationUser> UserManager;
    #endregion Private Members

    #region Constructor
    public DbSeeder(RvMusicalDbContext dbContext, RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
    {
        DbContext = dbContext;
        RoleManager = roleManager;
        UserManager = userManager;
    }
    #endregion Constructor

    #region Public Methods
    public async Task SeedAsync()
    {
        // Create the Db if it doesn’t exist
        DbContext.Database.EnsureCreated();
        // Create default Users
        if (await DbContext.Users.CountAsync() == 0) await CreateUsersAsync();
    }
    #endregion Public Methods

    #region Seed Methods
    private async Task CreateUsersAsync()
    {
        // local variables
        DateTime createdDate = new DateTime(2016, 03, 01, 12, 30, 00);
        DateTime lastModifiedDate = DateTime.Now;
        string role_Administrators = "Administrators";
        string role_Registered = "Registered";

        //Create Roles (if they doesn't exist yet)
        if (!await RoleManager.RoleExistsAsync(role_Administrators)) await RoleManager.CreateAsync(new IdentityRole(role_Administrators));
        if (!await RoleManager.RoleExistsAsync(role_Registered)) await RoleManager.CreateAsync(new IdentityRole(role_Registered));

        // Create the "Admin" ApplicationUser account (if it doesn't exist already)
        var user_Admin = new ApplicationUser()
        {
            UserName = "Admin",
            Email = "admin@opengamelist.com",
            CreatedDate = createdDate,
            LastModifiedDate = lastModifiedDate,
            Flags = 0,
            Type = 0
        };

        // Insert "Admin" into the Database and also assign the "Administrator" role to him.
        if (await UserManager.FindByIdAsync(user_Admin.Id) == null)
        {
            await UserManager.CreateAsync(user_Admin, "Pass4Admin");
            /// ERROR OCCURED HERE
            await UserManager.AddToRoleAsync(user_Admin, role_Administrators);
            // Remove Lockout and E-Mail confirmation.
            user_Admin.EmailConfirmed = true;
            user_Admin.LockoutEnabled = false;
        }

    #endregion Seed Methods


}

我想说角色成功保存了数据库。

请帮助解决问题。

4 个答案:

答案 0 :(得分:11)

在错误发生之前检查UserManager.CreateAsync调用的输出。我猜测你的用户没有被持久化,因此下一次调用因FK问题而失败。

如果您使用的是默认身份密码要求(就像我在尝试时那样),您会从用户创建调用中获得密码验证错误结果。

enter image description here

答案 1 :(得分:0)

您是否应确保用户admin具有ID

if (await UserManager.FindByIdAsync(user_Admin.Id) == null)

应该是

if (await UserManager.FindByIdAsync(user_Admin.Id) != null)

答案 2 :(得分:0)

我知道这已经回答了,但是我只需要添加解决方案即可,希望我可以避免其他可怜的灵魂免于重复我的错误.....

我的用户已创建...

我只是没有单击SQL Server Object Explorer上的“刷新”按钮。

:((真令人尴尬。我花了一个多小时来追踪这个问题。

答案 3 :(得分:0)

我有同样的问题。这就是解决方案;转到DBContext并删除继承的类中的用户。

之前:

public class MyDBContext : IdentityDbContext<MyUser>
{ }

之后:

public class MyDBContext : IdentityDbContext
{ }