这可能真的很明显,但我不确定为什么我的 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 应该与任一属性一起使用?