我有一张注册表,允许学校注册。除了明显的登录和一般细节,学校还可以从他们拥有的设施和认证列表中选择。
我的数据显示正常且可以绑定。
问题将数据输入链接器表不起作用,它会以我尝试过的两种方式抛出错误:
方法一:
MembershipUser membershipUser = null;
if (schoolRegisterModel != null)
{
if (null != DB)
{
school SchoolUser = new school();
SchoolUser.username = schoolRegisterModel.UserName;
SchoolUser.email = schoolRegisterModel.Email;
string sPassowrdSalt = Security.Instance().CreateSalt();
SchoolUser.password = Security.Instance().CreatePasswordHash(schoolRegisterModel.Password, sPassowrdSalt);
SchoolUser.password_salt = sPassowrdSalt;
..More data etc..
foreach (var item in schoolRegisterModel.Facilities)
{
if (item.@checked)
{
school_facility sf = new school_facility();
sf.facility_id = item.facility_id;
SchoolUser.school_facility.Add(sf);
}
}
foreach (var item in schoolRegisterModel.Accreditations)
{
if (item.@checked)
{
school_accreditation sa = new school_accreditation();
sa.accreditation_id = item.accreditation_id;
SchoolUser.school_accreditation.Add(sa);
}
}
DB.schools.Add(SchoolUser);
DB.SaveChanges();
错误: {“INSERT语句与FOREIGN KEY约束冲突\”FK_school_facility_facility \“。冲突发生在数据库\”MYDB \“,table \”dbo.facility \“,列'facility_id'。\ r \ n声明已被终止。“}
此外 - 我是否需要手动检索即将成为基于此插页生成的学校ID。此方法避免仅使用主表(school)将数据直接输入到链接器表中。
方法2:
相同的代码再次尝试直接更新主表(学校)认证和设施集合,我手动更新链接器表使用上一个查询生成的最新主键,代码如下:
MembershipUser membershipSuser = null;
if (schoolRegisterModel != null)
{
if (null != DB)
{
school SchoolUser = new school();
SchoolUser.username = schoolRegisterModel.UserName;
SchoolUser.email = schoolRegisterModel.Email;
string sPassowrdSalt = Security.Instance().CreateSalt();
SchoolUser.password = Security.Instance().CreatePasswordHash(schoolRegisterModel.Password, sPassowrdSalt);
SchoolUser.password_salt = sPassowrdSalt;
..More data etc..
// Linker data for facilities and accreditations.
// Facilities
foreach (var item in schoolRegisterModel.Facilities)
{
if (item.@checked)
{
school_facility sf = new school_facility();
sf.facility_id = item.facility_id;
sf.school_id = SchoolUser.school_id;
DB.school_facility.Add(sf);
}
}
// Accreditations
foreach (var item in schoolRegisterModel.Accreditations)
{
if (item.@checked)
{
school_accreditation sa = new school_accreditation();
sa.accreditation_id = item.accreditation_id;
sa.school_id = SchoolUser.school_id;
DB.school_accreditation.Add(sa);
}
}
m_DB.SaveChanges();
错误: {“INSERT语句与FOREIGN KEY约束冲突\”FK_school_facility_facility \“。冲突发生在数据库\”MYDB \“,table \”dbo.facility \“,列'facility_id'。\ r \ n声明已被终止。“}
如果你们知道我哪里出错了,请告诉我。似乎有更新链接器表日期的例子(无论如何我都需要它)但是找不到我的问题的例子...
提前致谢。
答案 0 :(得分:0)
看起来我找到了答案:
MVC: The INSERT statement conflicted with the FOREIGN KEY constraint
我的数据通过基本上没有包含正确的外键值(0 - 不存在),而且我的数据库正在抛出错误。很抱歉浪费时间阅读和感谢您的时间。我希望这可以帮助别人。
乔