我有两个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。