【发布时间】:2026-01-31 10:50:02
【问题描述】:
我有一个相关的PatientRegistry 表,它有三个相关的表,它们具有one-to-many 关系Country、State 和City。在迁移期间,默认 DeleteBehavior 设置为 Cascade,这在 database Update 期间给我一个错误。如果我将其更改为Restrict,我可以正确地seed。我试图在构建期间强制执行Restrictbehavior,但在播种期间我不断收到此错误,
未处理的异常:System.InvalidOperationException:关联 实体类型“City”和“PatientRegistry”之间已被切断,但 此关系的外键不能设置为空。如果 应该删除依赖实体,然后设置要使用的关系 级联删除。
如何防止构建过程中的级联删除行为?
我贴的是相关代码,
[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();
}
【问题讨论】:
-
为什么是
WithOne()? -
@IvanStoev,你说得对,我完全相反,,,,应该是
WithMany()
标签: c# entity-framework entity-framework-core asp.net-core-2.0 entity-framework-migrations