我对 EF 代码优先方法和关联的行为非常奇怪。我有两个实体:
public class GlobalKpiSectionn
{
public GlobalKpiSection()
{
this.Regions = new HashSet<Region>();
}
public virtual ICollection<Region> Regions { get; protected set; }
}
public class Region
{
public int RegionId { get; set; }
public bool IsMain { get; set; }
[Required]
public virtual GlobalKpiSection KpiSection { get; set; }
}
我需要 KiSection 属性上的必需属性才能获得级联删除。
问题如下 - 在此代码中:
var mainRegion = context.Regions.Single(x => x.RegionId == id);
mainRegion.IsMain = true;
context.SaveChanges();
I'm getting exception that Required field is not initialized. But it is present just not loaded. I don't what to write everywhere explicit includes for properties when I use this entity. What can I do to overcome this?
UPDATE
我确定其延迟加载问题的原因是:
var primaryRegion = context.Regions
.Include(x => x.KpiSection)
.Single(x => x.RegionId == id);
解决了问题,但这绝对是糟糕的解决方案。
这就是为什么你不应该使用数据注释。数据注释是错误的功能,因为它们同时进行映射和验证(违反单一责任) - 正如您所看到的,它并不总是您想要的。所以你当前的选择是:
- 关闭验证
context.Configuration.ValidateOnSaveEnabled = false
- 公开不可为空的
KpiSectionId
你的外键属性Region
实体(您不需要Required
导航属性上的属性)。
- 使用 Fluent API 代替数据注释:
Example:
modelBuilder.Entity<GlobalKpiSection>()
.WithMany(s => s.Regions)
.HasRequired(r => r.KpiSection);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)