我在 EF 5 和循环引用延迟加载方面遇到问题。
下图代表我的模型。
主要问题是在 Model 和 ModelProperties 类之间,因为 Model 包含 IEnumerable 导航属性,而 ModelProperty 包含 Model 导航属性。
所以这样的设计导致了下面的情况
您可以访问全尺寸图像 http://tinypic.com/r/2vskuxl/6
正如你可以想象的,这会导致非常大的问题,OutOfMemory 异常。
我能找到的唯一解决方案是禁用延迟加载并使用其他方法。但是延迟加载非常简化了我们的工作。 我希望有一个配置或属性可以帮助我通过延迟加载仅加载两层关系。
有什么办法可以实现这一点吗?
更新: 应Julie Lerman的要求,这里是EF的视觉模型。 我强调了导致问题的主要关系。 您还可以访问全尺寸 http://tinypic.com/r/30v15pg/6
更新2: 这是模型定义。
public class Model {
public int ModelID { get; set; }
public int BrandID {
get;
set;
}
public virtual Brand Brand { get; set; }
public string Logo { get; set; }
public string Name { get; set; }
public virtual ICollection<ModelProperty> ModelProperties {
get;
set;
}
}
public class ModelProperty {
public int ModelPropertyID {
get;
set;
}
public virtual int PropertyDefinitionID {
get;
set;
}
public virtual PropertyDefinition PropertyDefinition {
get;
set;
}
public virtual int ModelID {
get;
set;
}
public virtual Model Model {
get;
set;
}
public bool IsContainable {
get;
set;
}
public bool HasFilterDefinition {
get;
set;
}
public virtual ICollection<ModelPropertyValue> ModelPropertyValues {
get;
set;
}
public virtual ICollection<ModelPropertyMatchingFilter> ModelPropertyMatchingFilter {
get;
set;
}
}
还有一个 ModelProperty 的实体配置。
public class ModelPropertyEntityTypeConfiguration : EntityTypeConfiguration<ModelProperty> {
public ModelPropertyEntityTypeConfiguration() {
HasKey(p => p.ModelPropertyID);
HasRequired(p => p.PropertyDefinition).WithMany(s => s.ModelProperties).HasForeignKey(s => s.PropertyDefinitionID).WillCascadeOnDelete(false);
HasRequired(p => p.Model).WithMany(s => s.ModelProperties).HasForeignKey(s => s.ModelID).WillCascadeOnDelete(false);
HasMany(p => p.ModelPropertyValues).WithRequired(s => s.ModelProperty).HasForeignKey(s => s.ModelPropertyID).WillCascadeOnDelete(true);
HasMany(p => p.ModelPropertyMatchingFilter).WithRequired(s => s.ContainerModelProperty).HasForeignKey(s => s.ContainerModelPropertyID).WillCascadeOnDelete(false);
ToTable("dbo.ModelProperties");
}
}
更新3: 我不确定,但 Automapper 也会导致这种情况。因为 Entity Framework Profile 告诉 Autommaper 在运行时调用的数千个方法。
更新4: 这是 EFProf 堆栈跟踪: 您访问更大版本http://tinypic.com/r/21cazv4/6
更新5 您可以在此处查看示例项目:https://github.com/bahadirarslan/AutomapperCircularReference 在示例中,您可以通过快速观看轻松看到无限循环。
最佳答案
感谢您的更新。你这个模特看起来不错啊它肯定知道这只是 1:* 关系。拉迪斯拉夫(像往常一样)是正确的。 LL 不会导致问题......除了在序列化期间的一个地方。您是否有可能在服务中拥有您的代码?通过常规延迟加载,只有您明确提到的属性才会被延迟加载。但在序列化期间,序列化“提及”每个属性,因此它只会在整个图表中不断加载属性并导致循环依赖问题。对于服务,我们必须在返回数据之前关闭延迟加载(使用 context.configuration.lazyloadingenabled=false)。因此,在服务方法中,您可以预先加载、延迟加载或显式加载来获取图表,但然后在返回结果之前禁用延迟加载。
关于lazy-loading - Entity Framework 5循环延迟加载导致OutOfMemoryException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15455866/