如何使用 ef 对迁移构建强制执行 Restrict DeleteBehavior?
Posted
技术标签:
【中文标题】如何使用 ef 对迁移构建强制执行 Restrict DeleteBehavior?【英文标题】:How to enforce Restrict DeleteBehavior for migration build using ef? 【发布时间】:2018-07-26 22:18:16 【问题描述】:我有一个相关的PatientRegistry
表,它有三个相关的表,它们具有one-to-many
关系Country
、State
和City
。在迁移期间,默认 DeleteBehavior
设置为 Cascade
,这在 database Update
期间给我一个错误。如果我将其更改为Restrict
,我可以正确地seed
。我试图在构建期间强制执行Restrict
behavior,但在播种期间我不断收到此错误,
未处理的异常: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()
【参考方案1】:
完全错过了,应该是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);
【讨论】:
以上是关于如何使用 ef 对迁移构建强制执行 Restrict DeleteBehavior?的主要内容,如果未能解决你的问题,请参考以下文章