2014年10月27日 星期一

Entity Framework Code First 組織Fluent API 設定

Fluent API可以設定的功能比較多,但每一個欄位就要寫一行,越大的專案設定就會越多
可以透過EntityTypeConfiguration<T>來分類

一般的設定方式
public class DemoContext : DbContext
{
    public DbSet<Table1> Table1 { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Table1>().ToTable("Table1").HasKey(x => x.id);
        modelBuilder.Entity<Table1>().Property(x => x.id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
            .HasColumnName("sid")
            .HasColumnType("bigint");
        modelBuilder.Entity<Table1>().Property(x => x.s1)
            .IsRequired()
            .HasMaxLength(10)
            .IsFixedLength()
            .IsUnicode(false);
        modelBuilder.Entity<Table1>().Property(x => x.c1)
            .HasPrecision(18, 2);
        modelBuilder.Entity<Table1>().Property(x => x.t1)
            .IsRowVersion();
    }
}

分類後的設定方式
public class DemoContext : DbContext
{
    public DbSet<Table1> Table1 { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new Table1Configuration());
    }

    private class Table1Configuration : EntityTypeConfiguration<Table1>
    {
        public Table1Configuration()
        {
            this.ToTable("Table1").HasKey(x => x.id);
            this.Property(x => x.id)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
                .HasColumnName("sid")
                .HasColumnType("bigint");
            this.Property(x => x.s1)
                .IsRequired()
                .HasMaxLength(10)
                .IsFixedLength()
                .IsUnicode(false);
            this.Property(x => x.c1)
                .HasPrecision(18, 2);
            this.Property(x => x.t1)
                .IsRowVersion();
        }
    }
}