将ApplicationUser添加到数据库会导致外键冲突

时间:2017-02-18 21:06:02

标签: sql asp.net model-view-controller foreign-keys asp.net-identity

我有两个ApplicationUsers,Cursist和Lector的web应用程序:

public class ApplicationUser : IdentityUser
{
    public string Sex { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    //email inherited by IdentityUser
    ....
}

public class Cursist: ApplicationUser
{
    public Group Group { get; set; }
    public int GroupId { get; set; }
    ....
}

 public class Lector: ApplicationUser
{
    private IEnumerable<Group> _supervising;
    ....
}

这是我第一次在ApplicationUser上使用继承,这导致了一个持续的错误:

  

System.Data.SqlClient.SqlException:INSERT语句与FOREIGN KEY约束“FK_AspNetUserClaims_AspNetUsers_UserId”冲突。冲突发生在数据库“cvodb”,表“dbo.AspNetUsers”,列“Id”中。   声明已经终止。

错误的来源似乎来自此代码段:

 public async Task InitializeData()
    {
        _dbContext.Database.EnsureDeleted();
        if (_dbContext.Database.EnsureCreated())
        {
            await InitializeUsers();
            _dbContext.SaveChanges();
        }
    }

    private async Task InitializeUsers()
    {
        ApplicationUser user = new Cursist("Male", "fname", "lname", "b@b.b");
        await _userManager.CreateAsync(user, "password");
        await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, "Cursist"));
    }

更改后编辑 我设法通过向ApplicationUserId添加UserName来解决UserId冲突。这些类现在看起来像这样:

public class ApplicationUser : IdentityUser
{
    public string Sex { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    //email inherited by IdentityUser

    public ApplicationUser(string Sex, string fname, string lname, string email)
    {
        base.Email = email;
        //username fixes foreign key conflict?
        base.UserName = email;
        Sex = sex;
        FName = fname;
        LName = lname;
    }
}
 public class Cursist: ApplicationUser
{
    public Group Group { get; set; }
    // can be null
    public int? GroupId { get; set; }
}
//Lector class hasn't changed.

我在控制台中获得此输出(忽略拼写差异):

  

ALTER TABLE [AspNetUsers] ADD CONSTRAINT [FK_AspNetUsers_Groep_GroepId] FOREIGN KEY([GroepId])REFERENCES [Groep]([GroepId])ON DELETE NO ACTION;   Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory:Information:Executed DbCommand(0ms)[Parameters = [],CommandType ='Text',CommandTimeout = '30']

     

ALTER TABLE [AspNetUsers] ADD CONSTRAINT [FK_AspNetUsers_Groep_GroepId1] FOREIGN KEY([GroepId1])REFERENCES [Groep]([GroepId])ON DELETE NO ACTION;   Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory:Information:Executed DbCommand(0ms)[Parameters = [],CommandType ='Text',CommandTimeout = '30']

     

ALTER TABLE [AspNetUsers] ADD CONSTRAINT [FK_AspNetUsers_Groep_GroepId2] FOREIGN KEY([GroepId2])REFERENCES [Groep]([GroepId])ON DELETE NO ACTION;

我不知道为什么AspNetUsers正在创建3个groupIds实例?第一个实例和第二个实例不生成错误,但最后一个实例:

  

{Microsoft.EntityFrameworkCore.DbUpdateException:更新条目时发生错误。有关详细信息,请参阅内部异常---&GT; System.Data.SqlClient.SqlException:INSERT语句与FOREIGN KEY约束“FK_AspNetUsers_Groep_GroepId2”冲突。冲突发生在数据库“cvodb”,表“dbo.Groep”,列'GroepId'中。   声明已经终止。

我感觉它正在尝试链接Group对象,但是组可以是null值。我仍然不确定为什么有groupId,groupId1和groupId2。

我有一个名为Group的类和两个子类ClosedGroup和OpenGroup。它们应该使用相同的键GroupId,没有Group的实例。只有ClosedGroups和OpenGroups。

1 个答案:

答案 0 :(得分:1)

我打赌这个问题是这个问题最受欢迎的问题。尝试添加claim时,一个或多个模型错误会导致冲突。大多数时候user已成功创建,但由于模型错误,添加声明的过程会中断。首先,而不是火与火;忘记CreateAsync,将其分配给变量,如下所示:

    var user  = await _userManager
                        .CreateAsync(superadmin, "Password");

将鼠标悬停在user variable上以确定遇到的模型错误,如下图所示:

enter image description here

就我而言,我没有分配所需的Email字段。然后,您可以修复模型错误,冲突就会消失。干杯!