I'm configuring a database for ASP Identity and I've hit a snag.
I'm looking to create a One to Many
relationship between two tables, which are ApplicationUser
& OrganisationUnit
.
An OrganisationUnit can have multiple ApplicationUsers
, with an ApplicationUser
only belonging to one OrganisationUnit
When I add a migration and update the database I get an error during execution :-
System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.AspNetUsers_dbo.OrganisationUnits_OrganisationUnitRefId". The conflict occurred in database "DefaultConnection", table "dbo.OrganisationUnits", column 'OrganisationUnitId'.
Here are the tables I'm trying to create :-
public class ApplicationUser : IdentityUser
{
[Required]
[MaxLength(100)]
public string Forename { get; set; }
[Required]
[MaxLength(100)]
public string Surname { get; set; }
[Required]
public DateTime DateCreated { get; set; }
public Guid OrganisationUnitId { get; set; }
[ForeignKey("OrganisationUnitId")]
public virtual OrganisationUnit OrganisationUnit { get; set; }
}
public class OrganisationUnit
{
public OrganisationUnit()
{
ApplicationUsers = new List<ApplicationUser>();
}
public Guid Id { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
[Required]
[MaxLength(100)]
public string Telephone { get; set; }
public virtual ICollection<ApplicationUser> ApplicationUsers { get; set; }
}
In my seed method for the Configuration.cs have the following code :-
protected override void Seed(ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var ou = new OrganisationUnit()
{
Id = Guid.NewGuid(),
Name = "Group1",
Telephone = "1234567890",
};
var user = new ApplicationUser()
{
UserName = "SuperPowerUser",
Email = "[email protected]",
EmailConfirmed = true,
Forename = "Derek",
Surname = "Rivers",
DateCreated = DateTime.Now.AddYears(-3),
OrganisationUnitId = ou.Id
};
userManager.Create(user, "MySuperP@ssword!");
}
}
you should try :
With your syntax (only provinding a FK) you assume that the Organisation exists.