設置主鍵 modelBuilder.Entity<x>().HasKey(t => t.Name); 設置聯合主鍵 modelBuilder.Entity<x>().HasKey(t =>new{t.Name,t.ID} ); 取消資料庫欄位標識(取消自動增長) modelBuilder.Entit ...
- 設置主鍵
modelBuilder.Entity<x>().HasKey(t => t.Name); - 設置聯合主鍵
modelBuilder.Entity<x>().HasKey(t =>new{t.Name,t.ID} ); - 取消資料庫欄位標識(取消自動增長)
modelBuilder.Entity<x>().Property(t=>t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); - 設置資料庫欄位標識(自動增長)
modelBuilder.Entity<Teacher>().Property(t =>t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); - 設置欄位最大長度
modelBuilder.Entity<ClassA>().Property(t => t.Name).HasMaxLength(100); - 設置欄位為必需
modelBuilder.Entity<ClassA>().Property(t =>t.Id).IsRequired(); - 屬性不映射到資料庫
modelBuilder.Entity<ClassA>().Ignore(t => t.A); - 將屬性指定資料庫列名:
modelBuilder.Entity<ClassA>() .Property(t => t.A) .HasColumnName("A_a"); - 級聯刪除(資料庫預設是不級聯刪除的)
modelBuilder.Entity<Course>().HasRequired(t => t.Department).WithMany(t => t.Courses).HasForeignKey(d => d.DepartmentID).WillCascadeOnDelete(); - 設置為Timestamp
modelBuilder.Entity<OfficeAssignment>() .Property(t => t.Timestamp) .IsRowVersion(); - 表1對0..1(Instructor實體可以包含零個或一個OfficeAssignment)
modelBuilder.Entity<OfficeAssignment>().HasRequired(t => t.Instructor).WithOptional(t => t.OfficeAssignment); - 表1對1
modelBuilder.Entity<Instructor>().HasRequired(t => t.OfficeAssignment).WithRequiredPrincipal(t => t.Instructor); - 表1對n(Department為主表)
modelBuilder.Entity<Staff>() .HasRequired(c => c.Department) .WithMany(t => t.Staffs) - 指定外鍵名(指定表Staff中的欄位DepartmentID為外鍵)
modelBuilder.Entity<Staff>() .HasRequired(c => c.Department) .WithMany(t => t.Staffs) .Map(m => m.MapKey("DepartmentID")); - 表n對n
modelBuilder.Entity<Course>()
.HasMany(t => t.Instructors)
.WithMany(t => t.Courses) - 表n對n指定連接表名及列名
modelBuilder.Entity<Course>()
.HasMany(t => t.Instructors)
.WithMany(t => t.Courses)
.Map(m =>
{
m.ToTable("CourseInstructor");
m.MapLeftKey("CourseID");
m.MapRightKey("InstructorID");
});