【问题标题】:Define optional self-referencing one-many relationship with Fluent Api使用 Fluent Api 定义可选的自引用一对多关系
【发布时间】:2012-02-22 12:44:38
【问题描述】:
public class Attribute
{
    [Key]
    public int AttributeId { get; set; }

    [Required, StringLength(100)]
    public string Name { get; set; }

    public int ValueAttributeId { get; set; }
    public Attribute ValueAttribute { get; set; }

    public IList<Attribute> ValueAttributes { get; set; }
}

  modelBuilder.Entity<Attribute>()
     .HasOptional(a => a.ValueAttribute)
     .WithMany(a => a.ValueAttributes)
     .HasForeignKey(a => a.ValueAttributeId);

\tSystem.Data.Entity.Edm.EdmAssociationType: : 多重性与关系“Attribute_ValueAttribute”中角色“Attribute_ValueAttribute_Target”中的引用约束冲突。由于 Dependent Role 中的所有属性都不可为空,因此 Principal Role 的复数必须为“1”。

啊啊啊啊……

【问题讨论】:

  • 公共整数? ValueAttributeId { 获取;放; }
  • 顺便说一句 - 使用 EFCF 的部分好处是您不需要使用 [Key][Required] 等属性来装饰您的 POCO。
  • 是的...那么我可以避免从我的域中引用 EF。
  • 另外,您可能希望使用 virtual 关键字标记这些属性。
  • 我不喜欢延迟加载。 ;) 不必要的数据被加载和加载效率低下的可能性太大。

标签: c# entity-framework-4.3


【解决方案1】:
public int ? ValueAttributeId { get; set; }

...该属性需要可以为空。

【讨论】:

    猜你喜欢
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多