【译】第20节---数据注解-InverseProperty

原文:http://www.entityframeworktutorial.net/code-first/inverseproperty-dataannotations-attribute-in-code-first.aspx

我们已经学习,如果你没有在父类中包含外键属性,那么Code-First会创建{Class Name} _ {Primary Key}外键列。 当您在类之间有多个关系时,会使用InverseProperty属性。

请看以下示例:

public class Student
{
    public Student()
    { 
        
    }
    public int StudentID { get; set; }
    public string StudentName { get; set; }
        
    public Standard CurrentStandard { get; set; }
    public Standard PreviousStandard { get; set; }
}

public class Standard
{
    public Standard()
    { 
        
    }
    public int StandardId { get; set; }
    public string StandardName { get; set; }
    
    public ICollection<Student> CurrentStudents { get; set; }
    public ICollection<Student> PreviousStudents { get; set; }
   
    }

如上例所示,Student类包含两个导航属性到Standard类。 Standard类包括Student的两个集合导航属性。 Code-First为此关系创建四列,如下所示:

InverseProperty覆盖此约定并指定属性对齐。 以下示例使用Standard类中的InverseProperty来解决此问题:

public class Student
{
    public Student()
    { 
        
    }
    public int StudentID { get; set; }
    public string StudentName { get; set; }
        
    public Standard CurrentStandard { get; set; }
    public Standard PreviousStandard { get; set; }
}

public class Standard
{
    public Standard()
    { 
        
    }
    public int StandardId { get; set; }
    public string StandardName { get; set; }
    
    [InverseProperty("CurrentStandard")]
    public ICollection<Student> CurrentStudents { get; set; }
        
    [InverseProperty("PreviousStandard")]
    public ICollection<Student> PreviousStudents { get; set; }
   
}

如上例所示,我们已经将InverseProperty属性应用于CurrentStudents和PreviousStudents属性,并指定了它所属的Student类的参考属性。

这样,Code-First将在Student表中只创建两个外键列,如下所示:

你还可以使用Foreign Key属性来包含具有不同名称的外键属性,如下所示:

public class Student
{
    public Student()
    { 
        
    }
    public int StudentID { get; set; }
    public string StudentName { get; set; }
        
    public int CurrentStandardId { get; set; }
    public int PreviousStandardId { get; set; }

    [ForeignKey("CurrentStandardId")]
    public Standard CurrentStandard { get; set; }
        
    [ForeignKey("PreviousStandardId")]
    public Standard PreviousStandard { get; set; }
}

public class Standard
{
    public Standard()
    { 
        
    }
    public int StandardId { get; set; }
    public string StandardName { get; set; }
    
    [InverseProperty("CurrentStandard")]
    public ICollection<Student> CurrentStudents { get; set; }
        
    [InverseProperty("PreviousStandard")]
    public ICollection<Student> PreviousStudents { get; set; }
   
}

以上示例将创建以下列:

因此,你可以在相同类多个关系之间使用InverseProperty 和ForeignKey 属性。

原文地址:https://www.cnblogs.com/talentzemin/p/7218483.html