Peurr Peurr - 4 months ago 28
ASP.NET (C#) Question

ASP.NET Core Conflict with Foreign Key

I have got several models:


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; }


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; }


public class ApplicationUser : IdentityUser
public string Firstname { get; set; }
public string Surname { get; set; }
public bool Gender { get; set; }
public DateTime Birthdate { get; set; }
public string InviteCode { get; set; }

public Guid GroupId { get; set; }
public Group CurrentGroup { get; set; }
public ICollection<Group> PastGroups { get; set; }

Now when I try to register (using
) a user (not even trying to give the user a group) I receive this error:

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.

In my
I have added some logics for the relations between
(Students) and the Foreign Key:

protected override void OnModelCreating(ModelBuilder 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);\\

.HasOne(p => p.CurrentGroup)
.WithMany(b => b.Students)
.HasForeignKey(p => p.GroupId);

I don't know what this is exactly doing, but I've been browsing some Stackoverflow threads to come to this code (migrations weren't working without it).

I look forward to a solution for my problem. Once again, I'm not doing ANYTHING with the
yet when registering.

Thanks in advance!


not even trying to give the user a group

Well there's your problem, it's required.

Either provide a group, or make it optional by making the foreign key nullable (Guid? GroupId).

Because it's currently a non-nullable struct, it'll have a default value of all zeroes (Guid.Empty). This FK is not known in your database, resulting in the error you see.