I am having a hell of figuring the problem with code. I have .net project with Entity Framework as DAL. I am using MySQL Server 8.0. Everything is working fine except when I trying to seed data. I understand the error but I have tried everything to resolve it but to no avail. The error:
An error occurred while updating the entries. See the inner exception for details.
inner exception:
MySql.Data.MySqlClient.MySqlException: Cannot add or update a child row: a foreign key constraint fails ("dbs"."branches", CONSTRAINT "FK_Branches_CompanyProfiles_CompanyProfileId" FOREIGN KEY ("CompanyProfileId") REFERENCES "companyprofiles" ("Id") ON DELETE CASCADE ON UPDATE CA)
I have my domain model and seed data.
Domain model
public class CompanyProfile
{
public CompanyProfile()
{
Branches = new HashSet<Branch>();
}
public int Id { get; set; }
public string Name { get; set; }
public string CompanyCity { get; set; }
public string CompanyAddress { get; set; }
public string CompanyAddressTwo { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public virtual ICollection<CompanyBranch> Branches { get; }
}
public class Branch
{
public int Id { get; set; }
public string BranchCity { get; set; }
public string BranchName { get; set; }
public virtual int CompanyProfileId { get; set; }
public decimal BranchTarget { get; set; }
public virtual CompanyProfile CompanyProfile { get; set; }
}
Fluent API for relationship:
class CompanyProfileConfigurations : EntityTypeConfiguration<CompanyProfile>
{
public CompanyProfileConfigurations()
{
HasMany(t => t.Branches)
.WithRequired(x => x.CompanyProfile)
.HasForeignKey(z => z.CompanyProfileId);
}
}
Seed:
context.CompanyProfiles.AddOrUpdate(
c => c.Name,
new CompanyProfile { Name = "New Company Profile" }
);
context.Branches.AddOrUpdate(
b => b.BranchName,
new Branch { BranchName = "Main Office", CompanyProfileId = 1, BranchCity = "", BranchTarget = 0m }
);
Your assistance is greatly appreciated
What I have tried:
I have tried google but didn't find solution