Code First:Fluent API

DbContext类有一个OnModelCreating方法,可以在这里配置模型,该方法接收一个类型为DbModelBuilder的建造者,本文介绍的为Data Anotation的等价方法,这些代码是自解释的。

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // Configure Code First to ignore PluralizingTableName convention
            // If you keep this convention then the generated tables will have pluralized names.
            modelBuilder.Conventions.Remove();

            // Default Schema (EF6 onwards)
            modelBuilder.HasDefaultSchema("sales");

            // Configuring a Primary Key [Key]
            modelBuilder.Entity().HasKey(t => t.InstructorID);

            // Configuring a Composite Primary Key
            modelBuilder.Entity().HasKey(t => new { t.PassportNumber, t.IssuingCountry });

            // Switching off Identity for Numeric Primary Keys
            modelBuilder.Entity().Property(t => t.PassportNumber).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

            // Specifying the Maximum Length on a Property
            modelBuilder.Entity().Property(t => t.IssuingCountry).HasMaxLength(50);

            // Configuring the Property to be Required
            // (NOT NULL) [Required]
            modelBuilder.Entity().Property(t => t.Issued).IsRequired();

            // Specifying Not to Map a CLR Property to a Column in the Database
            // [NotMapped]
            modelBuilder.Entity().Ignore(t => t.BlogCode);

            // Mapping a CLR Property to a Specific Column in the Database
            // [Column("BlogTitle")]
            modelBuilder.Entity().Property(t => t.Title).HasColumnName("BlogTitle");

            // Configuring whether a String Property Supports Unicode Content
            // (varchar not nvarchar)
            modelBuilder.Entity().Property(t => t.Title).IsUnicode(false);

            // Configuring the Data Type of a Database Column [Column(TypeName = "varchar")]
            modelBuilder.Entity().Property(p => p.Name).HasColumnType("varchar");

            // Mapping an Entity Type to a Specific Table in the Database
            modelBuilder.Entity().ToTable("t_Department");

            // 第二个参数是SCHEMA
            modelBuilder.Entity().ToTable("t_Department", "school");

            // Specifying That a Class Is a Complex Type
            modelBuilder.ComplexType
(); // Specifying Not to Map a CLR Entity Type to a Table in the Database // [NotMapped] modelBuilder.Ignore(); // Configuring Properties on a Complex Type // Method 1 modelBuilder.ComplexType
().Property(t => t.Location).HasMaxLength(20); // Method 2 modelBuilder.Entity().Property(t => t.Details.Location).HasMaxLength(20); // Configuring a Property to Be Used as an Optimistic Concurrency Token modelBuilder.Entity().Property(t => t.Timestamp).IsConcurrencyToken(); // Configuring the property to be a row version in the database modelBuilder.Entity().Property(t => t.Timestamp).IsRowVersion(); }

 

你可能感兴趣的:(Code First:Fluent API)