一、概述
Fluent API 可以理解为一种从POCO到数据库的映射约定,包括字段长度,类型,主外键等等,在EF Code First进行开发时候经常用到。
1、主键
modelBuilder.Entity<Product>().HasKey(t => t.InstructorID);
联合主键
modelBuilder.Entity<BlogUser>().HasKey(user =>new { user.UserId, user.BlogName });
2、数值主键取消数据库自增
modelBuilder.Entity<Department>().Property(t => t.DepartmentID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
3、字段最大长度
modelBuilder.Entity<Department>().Property(t => t.Name).HasMaxLength(50);
4、字段不可为null
modelBuilder.Entity<Department>().Property(t => t.Name).IsRequired();
5、复杂类型
modelBuilder.ComplexType<Address>();
6、不映射
modelBuilder.Entity<User>().Ignore(user => user.MyProperty);
7、一对多(一个用户多个地址)
modelBuilder.Entity<Post>() .HasRequired(p =>p.User) .WithMany(user => user.Posts) .HasForeignKey(p => p.UserId);
8、表名、列名列类型
modelBuilder.Entity<MyUser>().ToTable("User");
modelBuilder.Entity<User>() .Property(user => user.Description) .HasColumnName("userDescription") .HasColumnType("ntext");
9、级联删除,重写方法OnModelCreating
public class PracticeEntitys : DbContext { public PracticeEntitys() : base("Name=Practice") { } public new Database Database { get { return base.Database; } } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); //base.OnModelCreating(modelBuilder); } public DbSet<Article> Articles { get; set; } }