Enity Framework Fluent APIs

Fluent API and annotations are you two options when it comes to controling mappings and configuring constraints such as field length or required. When configured these constraints it will affect the database that is created by Code First as well as the validation that is done by Entity Framework.

Some reasons to favour fluent APIs:

  • Annotations only cover a subset of the fluent API functionality.
  • Some test frameworks work better when Enitity Framework stuff isn’t scattered through your entitites.

There are two ways of using fluent APIs. First is simply to place them in the DbContext’s OnModelCreating method:

public class ApplicationDB : DbContext

{

    public ApplicationDB()

: base("name=EF5.Demo")

{ }

public DbSet<User> Users { get; set; }

protectedoverridevoid OnModelCreating(DbModelBuilder modelBuilder)

{

modelBuilder.Entity<User>().ToTable("tblUsers");

modelBuilder.Entity<User>().HasKey(x => x.ID);

modelBuilder.Entity<User>().Property(x =>x.CreatedDate).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

base.OnModelCreating(modelBuilder);

}

}

The second is to put each entities configuration into a seperate file:

public class ApplicationDB:DbContext

{

publicApplicationDB()

: base("name=EF5.Demo")

{}

publicDbSet<User> Users { get; set; }

protectedoverridevoid OnModelCreating(DbModelBuilder modelBuilder)

{

modelBuilder.Configurations.Add<User>(newProductConfiguration());

base.OnModelCreating(modelBuilder);

}

}

publicclassProductConfiguration : EntityTypeConfiguration<User>

{

public ProductConfiguration()

{

ToTable("Users");

HasKey(p => p.ID);

Property(p => p.CreatedDate).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

}

}
Advertisements