EntityFramework Code-First 简易教程(十)-------多对多
2016-07-03 10:49
399 查看
配置Many-to-Many(多对多)关系:
这里有两个类,Student和Course,一个Student可以有多个Course,一个Course也可以有多个Student,所以这就成了多对多关系。更多信息请访问Entity Relationship。进入正题:
1.使用DataAnnotation配置多对多关系:
Student类中有一个Course的集合属性,在Course类中也有一个Student的集合属性,这样就默认配置成了多对多关系。代码如下:public class Student { public Student() { } public int StudentId { get; set; } [Required] public string StudentName { get; set; } public int StdandardId { get; set; } public virtual ICollection<Course> Courses { get; set; } } public class Course { public Course() { this.Students = new HashSet<Student>(); } public int CourseId { get; set; } public string CourseName { get; set; } public virtual ICollection<Student> Students { get; set; } }
上面的代码将会创建如下的数据库,这里会新建一张表CourseStudents,这张新表里面记录着对多对关系的两个表的外键StudentId和CourseId(当然在CourseStudents表中这两列即是主键又是外键)。
2.使用Fluent API配置多对多关系:
直接上配置代码:protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Student>() .HasMany<Course>(s => s.Courses) .WithMany(c => c.Students) .Map(cs => { cs.MapLeftKey("StudentRefId"); cs.MapRightKey("CourseRefId"); cs.ToTable("StudentCourse"); }); }
如你所见,上面的例子中,
.HasMany<Course>(s => s.Courses).WithMany(c => c.Students)告诉Student和Course有多对多关系。
Map方法可以传入一个委托,所以这里可以使用lambda表达式,其中,MapLeftKey方法指定了Student的外键属性名称(这里先指定Student,所以它是左表)和Course表的外键,ToTable方法将创建StudentCourse表。
这样数据库将会创建一个新表StudentCourse,CourseRefId和StudentRefId既是主键又是外键。
到此,一对一,一对多,多对多的关系我们就讲完了,基本上能应对大多数情况的开发了。
相关文章推荐
- 7 款顶级开源 BI(商务智能)软件和报表工具
- caffe 学习系列之finetuning
- git命令cherrypick
- latex(2)排版论文《自动化学报》
- svn-clearup 报错的处理(Cleanup failed to process the following paths...)
- uC/OS-III 函数整理
- 前端工程师的Java路-一些唠叨与经验总结
- 189. Rotate Array
- csdn待改进点之29------>详情和列表的浏览数严重不一致,请不要说每次说缓存, 请不要说重现不了
- Python 也能干大事 —— 解方程
- 模拟APK版本更新
- CrackingtheCodeInterview之栈与队列
- SSH安装
- WPF EventSetter Handler Command
- NASA 美国国家航空航天局开源项目列表
- NLTK-自然语言工具包
- xamarin android webview XHR错误
- storm入门
- TSP问题之状态压缩dp法
- Leetcode add-two-numbers