3

这可能真的很明显,但我不确定为什么我的 InverseProperty 注释不能以其他方式工作。

我有这两个类(简化):

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 注释不起作用。我得到:

类型“PDguide.Models.Cluster”的属性“Dimensions”上的 InversePropertyAttribute 无效。属性“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 应该与任一属性一起使用?

4

1 回答 1

4

你说的对。在Programming Entity Framework: Code First 中,Lerman 和 Miller 在第 72 页上说

您可以将注释放在关系的任一端(如果需要,也可以放在两端)。

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

于 2013-09-05T12:16:24.620 回答