EF 4.1 RTM - EntityTypeConfiguration

时间:2011-04-19 15:38:58

标签: entity-framework code-first

我一直在使用EF Code First CTP5为每个实体提供专用的映射类,如下所示:

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");
    }
}

按照Jonas Cannehag所描述的方式加载它们: http://areaofinterest.wordpress.com/2010/12/08/dynamically-load-entity-configurations-in-ef-codefirst-ctp5/

但是这在RTM中不起作用,我无法弄清楚如何使用专用的映射类。你呢? : - )

1 个答案:

答案 0 :(得分:16)

public class DataContext : DbContext
{
  ...

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

动态版(可能应该在投入生产前进行广泛测试)

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);
        }