基本上sql中要表示继承关系有3中方式.
分别是,1表继承(TPH),2表继承(TPC),3表继承(TPT)
1表 :
Person
id type name classroom office
1 student keat 1B null
2 teacher xinyao null Lv2-T2
好处是不用 inner join 快,坏处是null 很多,浪费空间, column很长不好看。
2表:
这个很瞎不要学 .. , 大概就是没有父表,字表很多,但是每个column都重复写...无言
3表: (3只是代号,其实是看子类多少就多少表,子表的 id 是跟父表一样的)
Person
id name
Student
id classroom
Teacher
id office
这样就没有null了,只是要inner join 会慢
entity 是用 Fluent API 来实现的
3表方式
[Table("person")] public class Person { [Key] public Int32 id { get; set; } public string name { get; set; } } //子类不要写 [table("")]public class Student : Person { public string classroom { get; set; } }public class Teacher : Person { public string office { get; set; } }
Fluent API
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Person>(). //对Person Map<Student>(s => s.ToTable("student")). //map 另外2个table , "student" 是tableName Map<Teacher>(t => t.ToTable("teacher")); base.OnModelCreating(modelBuilder); }
insert 的话直接实例化字类就可以了
db.students.Add(new Student { name = "keatkeat", classroom = "1B" }); db.SaveChanges();
1表方式 :
[Table("person")] public class Person { [Key] public Int32 id { get; set; } public string name { get; set; } } /* 子类千万不要写 [Table()] 了 */ public class Student : Person { public string classroom { get; set; } } public class Teacher : Person { public string office { get; set; } }
Fluent API
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Person>() .Map<Student>(s => s.Requires("type").HasValue("student")) .Map<Teacher>(m => m.Requires("type").HasValue("teacher")); base.OnModelCreating(modelBuilder); }
时间: 2024-10-07 05:02:16