EF 4.4 InverseProperty并不完全相反

时间:2013-09-04 23:51:58

标签: entity-framework data-annotations

这可能是显而易见的,但我不确定为什么我的InverseProperty注释不起作用。

我有这2个课程(简化):

public class Cluster
{
    [Key]
    public int ClusterId { get; set; }

    [Required]
    [MaxLength(80, ErrorMessage = "DimensionCluster Name cannot be more than 80 characters in length.")]
    [Display(Name = "DimensionCluster Name")]
    public string ClusterName { get; set; }

    [InverseProperty("DimensionCluster")]
    public virtual IEnumerable<Dimension> Dimensions { get; set; }

}

public class Dimension
{
    [Key]
    public int DimensionId { get; set; }

    [Required]
    [MaxLength(80, ErrorMessage = "Dimension Name cannot be more than 80 characters in length.")]
    [Display(Name = "Dimension Name")]
    public string DimensionName { get; set; }

    [Required]
    [Display(Name = "Short Definition")]
    public string ShortDefinition { get; set; }

    [Required]
    [Display(Name = "DimensionCluster Name")]
    public int ClusterId { get; set; }

    [ForeignKey("ClusterId")]
    public virtual Cluster DimensionCluster { get; set; }


}

上面的InverseProperty注释不起作用。我明白了:

  

属性'Dimensions'上的InversePropertyAttribute类型   'PDguide.Models.Cluster'无效。物业'DimensionCluster'   不是相关类型的有效导航属性   'System.Collections.Generic.IEnumerable`1 [PDguide.Models.Dimension]'。   确保该属性存在且是有效的引用或集合   导航属性。

尝试了很多MSDN文档和SO答案。我终于尝试了另一种方式(下面的代码),它起作用了!

public class Cluster
{
    [Key]
    public int ClusterId { get; set; }

    [Required]
    [MaxLength(80, ErrorMessage = "DimensionCluster Name cannot be more than 80 characters in length.")]
    [Display(Name = "DimensionCluster Name")]
    public string ClusterName { get; set; }

    public virtual IEnumerable<Dimension> Dimensions { get; set; }

}

public class Dimension
{
    [Key]
    public int DimensionId { get; set; }

    [Required]
    [MaxLength(80, ErrorMessage = "Dimension Name cannot be more than 80 characters in length.")]
    [Display(Name = "Dimension Name")]
    public string DimensionName { get; set; }

    [Required]
    [Display(Name = "Short Definition")]
    public string ShortDefinition { get; set; }

    [Required]
    [Display(Name = "DimensionCluster Name")]
    public int ClusterId { get; set; }

    [ForeignKey("ClusterId")]
    [InverseProperty("Dimensions")]
    public virtual Cluster DimensionCluster { get; set; }

}

我已经阅读了某个地方(我现在无法找到该引用,或者我可能错误地推断出它),您可以在关系的任一端指定InverserProperty注释。但这似乎不是这样的情况?

我是否理解InverseProperty应该使用这两种属性?

1 个答案:

答案 0 :(得分:3)

你是对的。在编程实体框架:代码优先 Lerman和Miller在第72页说道

  

您可以将注释放在关系的任何一端(如果您,则可以放在两端)   想)。

当我查看当前的EF源时,似乎只有ICollection<T>类型的集合属性被识别为有效的反向属性。因此,我认为将Dimensions属性的类型更改为ICollection<Dimension>也可以将InversePropertyAttribute放在那里。