ASP.NET核心冲突与外键
问题描述:
我有几种模式:ASP.NET核心冲突与外键
Course.cs
public class Course
{
public Guid Id { get; set; }
public ICollection<ApplicationUser> Teacher { get; set; }
public string Name { get; set; }
public string ShortName { get; set; }
public DateTime CreationDate { get; set; }
public bool IsActive { get; set; }
}
Group.cs
public class Group
{
public Guid Id { get; set; }
public ApplicationUser Mentor { get; set;}
public string DisplayName { get; set; }
public string GroupName { get; set; }
public DateTime StartYear { get; set; }
public string InviteCode { get; set; }
public ICollection<ApplicationUser> Students { get; set; }
public ICollection<Course> Courses { get; set; }
}
ApplicationUser.cs
public class ApplicationUser : IdentityUser
{
[Required]
public string Firstname { get; set; }
[Required]
public string Surname { get; set; }
public bool Gender { get; set; }
public DateTime Birthdate { get; set; }
//[Required]
public string InviteCode { get; set; }
public Guid GroupId { get; set; }
[ForeignKey("GroupId")]
public Group CurrentGroup { get; set; }
public ICollection<Group> PastGroups { get; set; }
}
现在,当我尝试(使用Identity
)用户(甚至没有试图给用户一个组)我收到此错误登记:
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_AspNetUsers_Groups_GroupId". The conflict occurred in database "aspnet-Project_Dojo-3af15f80-8c62-40a6-9850-ee7a296d0726", table "dbo.Groups", column 'Id'. The statement has been terminated.
在我modelBuilder
我增加了一些逻辑的Group
之间的关系,ApplicationUser
(学生)和外键:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);\\
builder.Entity<ApplicationUser>()
.HasOne(p => p.CurrentGroup)
.WithMany(b => b.Students)
.HasForeignKey(p => p.GroupId);
}
我不知道这是什么做的究竟,但我一直在浏览一些线程#1来到这个鳕鱼e(没有它,移民工作就无法开展)。
我期待着解决我的问题。再一次,我在注册时还没有做任何与groups
。
提前致谢!
答
not even trying to give the user a group
那么这是你的问题,它是必需的。
要么提供一个组,要么通过使外键可为空(Guid? GroupId
)使其成为可选。
因为它目前是一个不可空的结构,它将有一个默认值为全零(Guid.Empty
)。此FK在您的数据库中未知,导致您看到的错误。
Change public Guid GroupId {get;组; } to public int GroupId {get;组; } –
我认为问题出现在多对多的关系中ApplicationUser-Group – tmg