我有一个与具有one-to-many
关系Country
,State
和City
的相关表相关的PatientRegistry
表。在迁移期间,默认的DeleteBehavior
设置为Cascade
,这在database Update
期间给了我错误。如果我将其更改为Restrict
,则可以正确使用seed
。我试图在构建过程中执行Restrict
的行为,但在播种过程中我一直遇到此错误
未经手的例外:system.invalidoperationException:关联 在实体类型之间,"城市"one_answers"患者报告"已被切断,但 这种关系的外键不能设置为无效。如果是 依赖实体应删除,然后设置要使用的关系 级联删除。
我如何防止在构建过程中删除级联反应?
我正在发布相对代码
[Table("PatientsRegistry")]
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; }
public int CountryId { get; set; }
public Country Country { get; set; }
public int StateId { get; set; }
public State State { get; set; }
public int CityId { get; set; }
public City City { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
public ICollection<PartnerRegistry> Partners { get; set; }
public PatientRegistry()
{
Partners = new Collection<PartnerRegistry>();
}
}
和我的OnModelCreating
builder.Entity<ApplicationUser>()
.HasOne(c => c.Country)
.WithOne()
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<ApplicationUser>()
.HasOne(c => c.State)
.WithOne()
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<ApplicationUser>()
.HasOne(c => c.City)
.WithOne()
.OnDelete(DeleteBehavior.Restrict);
我播种如下,
if (!context.PatientsRegistry.Any())
{
context.PatientsRegistry.AddRange(
new PatientRegistry
{
PatientFileId = 1111,
CountryId = context.Countries.Where(g => g.Name == "Jordan").SingleOrDefault().Id,
StateId = context.States.Where(g => g.Name == "Amman").SingleOrDefault().Id,
CityId = context.Cities.Where(g => g.Name == "Abu Nusair").SingleOrDefault().Id,
}
);
context.SaveChanges();
}
完全错过了它,应该是 WithMany()
builder.Entity<ApplicationUser>()
.HasOne(c => c.Country)
.WithMany()
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<ApplicationUser>()
.HasOne(c => c.State)
.WithMany()
.OnDelete(DeleteBehavior.Restrict);
builder.Entity<ApplicationUser>()
.HasOne(c => c.City)
.WithMany()
.OnDelete(DeleteBehavior.Restrict);