ForeignKey 和 InverseProperty 属性是否始终应用于 EF6.x 中的多边

Are ForeignKey and InverseProperty attributes always applied on the many side in EF6.x

我在我的项目中使用 Entity Framework 6.0 代码优先方法。

我有两个实体 - entity1entity2 具有一对多关系,因此 entity1 的一个实例可以有一个或多个 entity2 的实例和一个 entity2[=33 的实例=] 只有一个实例 entity1.

问题:对于上述情况,ForeignKey 属性是否总是在 entity2 class 的定义中被提及,或者它也可以在entity1class中指定定义?同样,对于 InverseProperty 属性是否有硬性规定必须始终为 entity2 指定?

更新 1

似乎 ForeignKey 必须始终在关系多端的实体(即依赖实体)中提及,而 InverseProperty 必须始终在关系一侧的实体(即主体实体)中指定。但是,我不确定。

ForeignKeyAttribute

The annotation may be placed on the foreign key property and specify the associated navigation property name, or placed on a navigation property and specify the associated foreign key name.

对于一对多关系,只有 "many" 端的实体有外键开头,因此只能在该端使用。

InversePropertyAttribute

Specifies the inverse of a navigation property that represents the other end of the same relationship.

关系有两端,属性可以放在两端。

  • 对于一对多关系,这里有一个放在"one"端的例子:

    public class Post 
    { 
        public Person CreatedBy { get; set; } 
        public Person UpdatedBy { get; set; }
    }
    
    public class Person 
    { 
        public int Id { get; set; } 
        public string Name { get; set; } 
    
        [InverseProperty("CreatedBy")] 
        public List<Post> PostsWritten { get; set; } 
    
        [InverseProperty("UpdatedBy")] 
        public List<Post> PostsUpdated { get; set; }
    }
    

    https://msdn.microsoft.com/en-us/data/jj591583.aspx#Relationships

  • 这是 "many" 方面的示例:

    [Table("Department", Schema = "dbo")]  
    public class DepartmentMaster  
    {  
        public ICollection<Employee> PrimaryEmployees { get; set; }  
        public ICollection<Employee> SecondaryEmployees { get; set; }  
    }  
    
    [Table("Employee", Schema = "dbo")]  
    public class Employee  
    {  
        [InverseProperty("PrimaryEmployees")]  
        public DepartmentMaster PrimaryDepartment { get; set; }  
    
        [InverseProperty("SecondaryEmployees")]  
        public DepartmentMaster SecondaryDepartment { get; set; }  
    }  
    

    http://www.c-sharpcorner.com/UploadFile/ff2f08/entity-framework-code-first-data-annotations/