Entity framework core 如何在ef中向具有可选关系的表中插入值?
我有两个实体,Entity framework core 如何在ef中向具有可选关系的表中插入值?,entity-framework-core,asp.net-core-2.0,Entity Framework Core,Asp.net Core 2.0,我有两个实体,PatientRegistry和PatientAccount。它们之间的关系是1-0..1。我试图在我的主表PatientRegistry中进行种子设定,但我的可选表PatientAccount中的必填字段不断出现空错误,我如何在主表中插入值而不必在可选表中进行种子设定 未处理的异常:Microsoft.EntityFrameworkCore.DbUpdateException: 更新条目时出错。查看内部异常 有关详细信息。-->System.Data.SqlClient.SqlE
PatientRegistry
和PatientAccount
。它们之间的关系是1-0..1。我试图在我的主表PatientRegistry
中进行种子设定,但我的可选表PatientAccount
中的必填字段不断出现空错误,我如何在主表中插入值而不必在可选表中进行种子设定
未处理的异常:Microsoft.EntityFrameworkCore.DbUpdateException:
更新条目时出错。查看内部异常
有关详细信息。-->System.Data.SqlClient.SqlException:无法插入
表“Password”列中的值为NULL
“ArtCoreDb.dbo.AspPatientsAccount”;列不允许空值。
更新失败
仅当我添加
PatientAccount =
new PatientAccount {
PatientFileId = 1111,
CountryCodeId = context.Countries.Where (g => g.Name == "United States of America").SingleOrDefault ().Id,
AreaCode = 424,
Email = "aamaizar@gmail.com",
MobileNo = "3244990",
IsConfirmedEmailAddress = false,
IsConfirmedPhoneNumber = false,
IsLocked = false,
Password = "213123",
},
事实上,我希望能够在PatientsRegistry
表中插入,而无需插入patientascount
,使用Add
(或AddRange
)标记图形中处于添加状态的所有可访问实体,我只需在种子设定期间将patientascount
属性添加到我的对象中
new PatientRegistry { PatientFileId = 1111, FirstName = "John", PatientAccount = {.......} }
试试这个代码
new PatientRegistry{
FirstName=“John”,
PatientAccount=null
}
你的示例代码运行正常,所以我怀疑真正的代码不同。
if (!context.PatientsRegistry.Any ()) {
context.PatientsRegistry.AddRange (
new PatientRegistry {
PatientFileId = 1111,
FirstName = "John"
}
);
context.SaveChanges ();
}
PatientAccount =
new PatientAccount {
PatientFileId = 1111,
CountryCodeId = context.Countries.Where (g => g.Name == "United States of America").SingleOrDefault ().Id,
AreaCode = 424,
Email = "aamaizar@gmail.com",
MobileNo = "3244990",
IsConfirmedEmailAddress = false,
IsConfirmedPhoneNumber = false,
IsLocked = false,
Password = "213123",
},
new PatientRegistry { PatientFileId = 1111, FirstName = "John", PatientAccount = {.......} }