Entity Framework Code-First(9.9):DataAnnotations - ForeignKey Attribute
2016-07-05 16:39
302 查看
DataAnnotations - ForeignKey Attribute:
ForeignKey attribute can be applied to properties of a class. Default Code-First convention for ForeignKey relationship expects foreign key property name match with primary key property.Consider the following example.
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; } }
As you can see in the above code, Student class includes foreign key StandardId, which is key property in Standard class. So now, Code First will create StandardId column in Students class as shown below.
ForeignKey attribute overrides this convention. You can have a different name of a foreign key property name than the primary key of a dependent class.
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; } }
As you can see in the above example, Student class includes StandardRefId foreign key property name instead of StandardId. We specify it using ForeignKey attribute on Standard navigation property so that Code-First will consider StandardRefId as foreign key, as shown below.
ForeignKey attribute can be applied to key property to specify which navigation property it points to, as shown below.
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; } }
Thus, you can use ForeignKey attribute to give a different name to a foreign key property.
相关文章推荐
- openstack M版安装 network(neutron)服务篇
- 【WCF服务自我寄宿】
- SAP的RFC接口的发布与JAVA调用
- 队列和栈
- PagerSlidingTabStrip源码解析
- Tomcat 8 .war文件部署出错
- 正则表达式验证url、时间、ip
- Arrays.asList方法的漏洞
- 08、js内的数据类型转换
- Linux配置多个Tomcat同时运行以及tomcat 的端口介绍
- UE4——HelloWorld
- PrintWriter类
- 【HTML5开发系列】meta元素详解
- Pureftpd
- InstallShield程序打包图解
- IIS7.0 Appcmd 命令详解
- Entity Framework Code-First(9.8):DataAnnotations - Column Attribute
- Wireshark网络抓包工具--过滤
- 例题10-13 UVA - 580 Critical Mass 危险的组合(递推)
- impdp导入遇到的问题