Configuration of Entity Framework Code First is a necessary evil and you have to admit is a very well designed user friendly process. But, in typical Microsoft fashion, the EF developers have given us more than one way to perform this configuration.
- Fluent API
- Fluent expression based configuration
- Performed during the OnModelCreating process of the DbContext.
- Allows for complex configurations that are not possible via Attribute based configuration
Fluent Configuration
- protected override void OnModelCreating(DbModelBuilder modelBuilder) {
- modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
- modelBuilder.Entity<Model>().HasMany(x => x.AvailableEngines)
- .WithMany(x => x.AvailableOn)
- .Map(x => x.MapLeftKey("ModelId")
- .MapRightKey("EngineId")
- .ToTable("ModelEngine"));
- modelBuilder.Entity<Model>().Ignore(x => x.SomeDerivedProperty);
- base.OnModelCreating(modelBuilder);
- }
- Attributes
- Attribute based configuration
- Performed directly on the Domain Model Class/Property being configured
- Allows the non-EF specific attributes to be used in other pieces of your application
- Allows validation of your Model at any time
Attribute Configuration
- public class Manufacturer {
-
- public long ManufacturerId { get; set; }
-
- [StringLength(40)]
- [Required]
- public string Name { get; set; }
-
- [Required]
- [StringLength(40)]
- public string Country { get; set; }
-
- [Required]
- public DbGeography Location { get; set; }
-
- #region << Relationships >>
-
- public virtual IList<Model> Models { get; set; }
-
- #endregion
-
- }
So…When do you use which!?
Use Fluent Configuration When:
- Configuration is being done solely to make the database behave correctly.
- Configuration has no effect on the design and/or behavior of your Domain Model.
- Examples:
- Specifying the database table the Domain Model is to be mapped to
- Specifying the database table column the Domain Model Field is to be mapped to
- Ignoring a Domain Model Field
- Configuring the keys and table names for relationships not able to be picked up by EF
Use Attribute Configuration When:
- Configuration solely applies to your Domain Model.
- Configuration has no effect on the design and/or behavior of your Database.
- Examples:
- Making a field Required
- Validating a field (String length, Range, etc.)
- Also…Don’t forget that for the most part these Attributes are not EF specific and can be used in the UI with MVC.