Skip to content

Latest commit

 

History

History
46 lines (34 loc) · 1.54 KB

12. Fluent API.md

File metadata and controls

46 lines (34 loc) · 1.54 KB

Fluent API

Entity Framework has many ways to specify how classes are mapped to tables (some would say it has too many ways!). In some cases, this need is minimal. In other cases, not so.

For instance, if the database tables we're working against don't match our entity classes, we will have to fix that somehow. Fortunately there is a (relatively) easy way to do this.

Assume that our Semester class maps to a table called year_semesters, and that the properties in our class don't have the same names as the columns in the table. We can then create a special map class, which maps our entity class to the table:

using System.Data.Entity.ModelConfiguration;

class SemesterMap : EntityTypeConfiguration<Semester>
{
	public SemesterMap()
	{
		ToTable("year_semesters");
		
		HasKey(t => t.ID);
		
		Property(t => t.ID).HasColumnName("semester");
		Property(t => t.Name).HasColumnName("sem_name");
		// Etc., for other properties with different names
	}
}

Then, in our DataContext class, we must remember to add an instance of that class to the OnModelCreating method:

	protected override void OnModelCreating(DbModelBuilder modelBuilder)
	{
		modelBuilder.Configurations.Add(new SemesterMap());
		// Etc., for other EntityMap classes we might need
	}

The need for this is probably the most when working against a legacy database, where the naming conventions don't match those used in our codebase.

Also note that the FluentAPI has a lot more to offer, but we won't cover more features here.