Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4.1 RTM - EntityTypeConfiguration

I have been using EF Code First CTP5 with dedicated mapping classes for each entity, like this:

public class UserMapping : EntityTypeConfiguration<User>
{
    public UserMapping()
    {
        ToTable("Users");

        HasKey(t => t.ID);
        Property(t => t.ID).HasColumnName("user_id");

        Property(t => t.Name).HasColumnName("name");
    }
}

And loading them the way Jonas Cannehag describes here: http://areaofinterest.wordpress.com/2010/12/08/dynamically-load-entity-configurations-in-ef-codefirst-ctp5/

But that doesn't work in RTM and I haven't been able to figure out how to use dedicated mapping classes. Have you? :-)

like image 680
Tommy Jakobsen Avatar asked Apr 19 '11 15:04

Tommy Jakobsen


1 Answers

public class DataContext : DbContext
{
  ...

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

dynamic version (probably should test extensive before putting in production)

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
            var typesToRegister =
                Assembly.GetExecutingAssembly().GetTypes().Where(
                    type =>
                    type.BaseType.IsGenericType &&
                    type.BaseType.GetGenericTypeDefinition() == typeof (EntityTypeConfiguration<>));

            foreach (object configurationInstance in typesToRegister.Select(Activator.CreateInstance))
            {
                modelBuilder.Configurations.Add((dynamic) configurationInstance);
            }

            base.OnModelCreating(modelBuilder);
        }
like image 130
mxmissile Avatar answered Nov 11 '22 00:11

mxmissile