FluentAPI详细用法
Posted 程序猿基础知识随笔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FluentAPI详细用法相关的知识,希望对你有一定的参考价值。
- 设置主键
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");
});
以上是关于FluentAPI详细用法的主要内容,如果未能解决你的问题,请参考以下文章