Table of Contents

IT:AD:EF/CodeFirst:HowTo:Define Models/Properties

Examples: Properties

The following just specify contraints on size, key, etc.

Primary Key

It's done automatically if you the fieldname is called Id or TheEntitityId, but if you can't use that field name:

modelBuilder.Entity<Manager>()
  .HasKey(ma => ma.ManagerCode);

Composite Keys

Use an anonymous object:

modelBuilder.Entity<Department>()
  .HasKey(t => new { t.DepartmentID, t.Name });

MaxLength

modelBuilder.Entity<Manager>().Property(ma => ma.Name)
  .HasMaxLength(20);

Required

modelBuilder.Entity<Department>().Property(dp => dp.Name)
  .IsRequired();

Ignore

You can ignore calculated columns:

modelBuilder.Entity<Department>().Ignore(t => t.Budget);

Mapping to a different Column

modelBuilder.Entity<Department>().Property(t => t.Name)
  .HasColumnName("DepartmentName");

CheckList: Class Properties