【发布时间】:2016-11-22 11:01:26
【问题描述】:
我有几个模型:
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:INSERT 语句与 FOREIGN KEY 冲突 约束“FK_AspNetUsers_Groups_GroupId”。冲突发生在 数据库“aspnet-Project_Dojo-3af15f80-8c62-40a6-9850-ee7a296d0726”, 表“dbo.Groups”,列“Id”。声明已终止。
在我的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);
}
我不知道这到底在做什么,但我一直在浏览一些 Stackoverflow 线程来查看这段代码(没有它,迁移就无法工作)。
我期待我的问题的解决方案。再一次,我在注册时还没有对groups 做任何事情。
提前致谢!
【问题讨论】:
-
更改公共 Guid GroupId { get;放; } to public int GroupId { get;放; }
-
我认为问题在于ApplicationUser-Group的多对多关系
标签: asp.net entity-framework asp.net-core asp.net-identity asp.net-core-mvc