【译】第18节---数据注解-ForeignKey

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

ForeignKey属性可以应用于类的属性。对于ForeignKey关系, 默认Code First约定期望外键属性名与主键属性相匹配。

看以下示例:

public class Student
{
    public Student()
    { 
        
    }
    public int StudentID { get; set; }
    public string StudentName { get; set; }
        
    //Foreign key for Standard
    public int StandardId { get; set; }

    public Standard Standard { get; set; }
}

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

正如你在上面的代码中可以看到的,Student类包括外键StandardId,它是Standard类中的主键属性。 所以现在,Code First将在Students类中创建StandardId列,如下所示:

ForeignKey属性覆盖此约定。 你可以具有与依赖类的主键不同的外键属性名称。

public class Student
{
    public Student()
    { 
        
    }
    public int StudentID { get; set; }
    public string StudentName { get; set; }
        
    //Foreign key for Standard
    public int StandardRefId { get; set; }

    [ForeignKey("StandardRefId")]
    public Standard Standard { get; set; }
}

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

如上例所示,Student类包括StandardRefId外键属性名称而不是StandardId。 我们使用标准导航属性中的ForeignKey属性指定它,以便Code-First将将StandardRefId视为外键,如下所示:

ForeignKey属性可以应用于key属性来指定它指向哪个导航属性,如下所示:

public class Student
{
    public Student()
    { 
        
    }
    public int StudentID { get; set; }
    public string StudentName { get; set; }
        
    //Foreign key for Standard
    
    [ForeignKey("Standard")]
    public int StandardRefId { get; set; }

    public Standard Standard { get; set; }
}

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

因此,你可以使用ForeignKey属性为外键属性指定不同的名称。

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