【问题标题】:ASP.NET Core Conflict with Foreign KeyASP.NET Core 与外键冲突
【发布时间】: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 中,我为GroupApplicationUser(学生)和外键之间的关系添加了一些逻辑:

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


【解决方案1】:

甚至没有尝试给用户一个组

那是你的问题,它是必需的。

要么提供一个组,要么通过使外键为空 (Guid? GroupId) 使其成为可选。

因为它目前是一个不可为空的结构,所以它的默认值全为零 (Guid.Empty)。此 FK 在您的数据库中是未知的,导致您看到的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 2015-05-17
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多