【发布时间】:2019-04-01 10:39:30
【问题描述】:
我仍在学习 EF Core,但在尝试仅将用户数据(没有 BusinessUserProfile 和 BusinessCompany)插入数据库时遇到错误。我有以下表格:用户、BusinessUserProfile 和 BusinessCompany。关系是User有一个BusinessUserProfile,BusinessCompany有多个BusinessUserProfile。
我的类是这样创建的:
用户模型类:
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public BusinessUserProfile BusinessUserProfile { get; set; }
public User()
{
BusinessUserProfile = new BusinessUserProfile();
}
}
BusinessUserProfile 模型类:
public class BusinessUserProfile
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public BusinessCompany BusinessCompany { get; set; }
public int BusinessCompanyId { get; set; }
public User User { get; set; }
public int UserId { get; set; }
}
}
BusinessCompany 模型类:
public class BusinessCompany
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<BusinessUserProfile> BusinessUserProfiles { get; set; }
public BusinessCompany()
{
BusinessUserProfiles = new Collection<BusinessUserProfile>();
}
}
DataContext.cs:
modelBuilder.Entity<User>()
.HasOne(u => u.BusinessUserProfile)
.WithOne(bup => bup.User)
.HasForeignKey<BusinessUserProfile>(bup => bup.UserId);
modelBuilder.Entity<BusinessCompany>()
.HasMany(bc => bc.BusinessUserProfiles)
.WithOne(bup => bup.BusinessCompany)
.HasForeignKey(bup => bup.BusinessCompanyId);
当我将用户添加到数据库时,出现错误:
MySqlException:无法添加或更新子行:外键约束失败(mydb.businessuserprofiles,CONSTRAINT FK_BusinessUserProfiles_BusinessCompanies_BusinessCompanyId FOREIGN KEY (BusinessCompanyId) REFERENCES businesscompanies (id) ON DELETE C)。
谁能给我建议?
【问题讨论】:
标签: mysql ef-core-2.0