具有所需关联的实体框架4.3 [英] Entity framework 4.3 with required association
问题描述
使用EF代码优先方法和关联,我的行为非常奇怪.我有两个实体:
I'm a very strange behavior with EF code first approach and associations. I have two entities:
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属性上的required属性,以便进行级联删除.
I need required attribute on KiSection property in order to get cascade deletes.
问题出在下面-此代码中:
The problem is the following - in this code:
var mainRegion = context.Regions.Single(x => x.RegionId == id);
mainRegion.IsMain = true;
context.SaveChanges();
我收到一个例外,该字段未初始化Required字段.但是存在只是没有加载.当我使用此实体时,我不会在任何地方写任何包含属性的显式包含内容.我该怎么做才能克服这个问题?
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?
更新
我确定其延迟加载问题的原因是:
The reason why I'm sure its lazy loading issue is that:
var primaryRegion = context.Regions
.Include(x => x.KpiSection)
.Single(x => x.RegionId == id);
解决了这个问题,但是绝对可以解决.
Solves the issue, but its definitely awful solution.
推荐答案
这就是为什么您不应该使用数据注释的原因.数据注释是错误的功能,因为它们同时进行映射和验证(违反单一职责)-如您所见,它并不总是您想要的.因此,您当前的选择是:
That is why you should not use data annotations. Data annotations are wrong feature because they do both mapping and validation (violation of single responsibility) - as you see it is not always what you want. So your current options are:
- 关闭
context.Configuration.ValidateOnSaveEnabled = false
中的验证
- 在您的
Region
实体中公开不可为空的KpiSectionId
外键属性(在导航属性中不需要Required
属性). - 使用流畅的API代替数据注释:
- Turn off validation in
context.Configuration.ValidateOnSaveEnabled = false
- Expose non nullable
KpiSectionId
foreign key property in yourRegion
entity (you will not needRequired
attribute on your navigation property). - Use fluent API instead of data annotations :
示例:
modelBuilder.Entity<GlobalKpiSection>()
.WithMany(s => s.Regions)
.HasRequired(r => r.KpiSection);
这篇关于具有所需关联的实体框架4.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!