【问题标题】:Are there any naming conventions for multiple inverse properties in EF Core or are attributes necessary?EF Core 中的多个逆属性是否有任何命名约定,或者是否需要属性?
【发布时间】:2018-04-27 22:56:41
【问题描述】:

This article 显示下表示例:

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public string Description { get; set; }

    [ForeignKey("OnlineTeacher")]
    public int? OnlineTeacherId { get; set; }
    public Teacher OnlineTeacher { get; set; }

    [ForeignKey("ClassRoomTeacher")]
    public int? ClassRoomTeacherId { get; set; }
    public Teacher ClassRoomTeacher { get; set; }
}

public class Teacher
{
    public int TeacherId { get; set; }
    public string Name { get; set; }

    [InverseProperty("OnlineTeacher")]
    public ICollection<Course> OnlineCourses { get; set; }
    [InverseProperty("ClassRoomTeacher")]
    public ICollection<Course> ClassRoomCourses { get; set; }
}

我发现我可以删除 [ForeignKey(*)] 属性,它们仍然可以在 Courses 表中正确创建。但是,如果我同时删除 [InverseProperty] 属性,EF 在我构建时会引发错误。仅like the foreign keys 是否有命名约定?我的目标是严格遵循命名约定并减少基于属性/流利的配置的数量。

【问题讨论】:

  • 您可以使用nameof 做得更好,例如[InverseProperty(nameof(Course.ClassRoomTeacher))]

标签: c# entity-framework-core


【解决方案1】:

如果我删除 BOTH [InverseProperty] 属性,EF 会抛出错误 当我建立。是否有这样的命名约定,就像 外键?

当两个实体之间存在许多相同类型的关联(例如一对多)时,EF 定义了没有命名约定

例如,当您在 EntityAEntityB 之间有一个关联时。假设它在EntityAEntityB 之间存在一对* 关系,当您遵守约定时它工作得很好。但是,当您在 EntityAEntityB 之间添加另一个 1 对 * 关系时,EF 将需要您的帮助来了解关联是如何关联的。所以你必须使用InverseProperty数据注解属性或者通过流利的配置定义完整的关系。

【讨论】:

  • 不幸的是,这就是我所怀疑的。我认为将逆属性(ICollection&lt;EntityA&gt;)命名为 就像 EntityA_Items { get; set; } 应该很容易让 EF 弄清楚,特别是因为它已经可以与外键一起使用.
猜你喜欢
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 2011-08-20
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多