我有这两个实体,PatientRegistry
和PatientAccount
。他们之间的关系是1-0..1。我正在尝试在我的主表PatientRegistry
中播种,但我在可选表PatientAccount
中的必填字段中仍然出现空错误。如何在主表中插入值而无需在我的主表中播种表也是?
未处理的异常:Microsoft.EntityFrameworkCore.DbUpdateException: 更新条目时发生错误。查看内部异常 详情。 ---> System.Data.SqlClient.SqlException:无法插入 值为NULL的表'密码',表 'ArtCoreDb.dbo.AspPatientsAccount';列不允许空值。 更新失败。
public class PatientRegistry {
[DatabaseGenerated (DatabaseGeneratedOption.Identity)]
[Display (Name = "Record Id")]
public long RecordId { get; set; }
[Key, DatabaseGenerated (DatabaseGeneratedOption.None)]
[Display (Name = "Patient File Number")]
public long PatientFileId { get; set; }
[Required, StringLength (50)]
[Display (Name = "First Name")]
public string FirstName { get; set; }
public virtual ICollection<PartnerRegistry> Partners { get; set; }
public virtual PatientAccount PatientAccount { get; set; }
}
public class PatientAccount {
[Key, DatabaseGenerated (DatabaseGeneratedOption.Identity)]
public long RecordId { get; set; }
[Required]
public string Password { get; set; }
[Required, StringLength (15)]
public string MobileNo { get; set; }
public bool IsConfirmedPhoneNumber { get; set; } = false;
public bool IsConfirmedEmailAddress { get; set; } = false;
public bool IsLocked { get; set; } = false;
public int? FailedAttempts { get; set; }
public DateTimeOffset? LastLoggedIn { get; set; }
public DateTimeOffset DateCreated { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
public long? PatientFileId { get; set; }
public virtual PatientRegistry PatientFile { get; set; }
}
我的流利API,
protected override void OnModelCreating (ModelBuilder builder) {
base.OnModelCreating (builder);
builder.Entity<PatientRegistry> ()
.HasOne (a => a.PatientAccount)
.WithOne (b => b.PatientFile)
.HasForeignKey<PatientAccount> (c => c.PatientFileId)
.OnDelete (DeleteBehavior.Cascade);
}
我种子,
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",
},
实际上,我希望能够插入PatientsRegistry
表而无需插入PatientAccount
答案 0 :(得分:0)
使用Add
(或AddRange
)标记图表中所有可访问的实体处于添加状态,我只需在播种期间向我的对象添加PatientAccount
道具
new PatientRegistry { PatientFileId = 1111, FirstName = "John", PatientAccount = {.......} }