【译】第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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值