mercredi 7 juin 2017

Howto Dynamic map properties of T in Entity Framework

Using Entity Framework I can in MyContext override the OnModelCreating methode and do stuff like:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
      //...
      modelBuilder.Entity<MyEntity>()
            .Property(x => x.Foo.Value)
            .HasColumnName("Foo");
      modelBuilder.Entity<OtherEntity>()
            .Property(x => x.Bar.Value)
            .HasColumnName("Bar");
  }

However, I don't want to specify this mapping for every EntityType in MyContext. I would like to define the pattern in a more generic way (propebly using reflextion). Somthing like

var types = Assembly.GetCallingAssembly().GetTypes();
foreach(var type in types){
    var props = type.GetProperties().Where(p => p.PropertyType is ISomeInterface);
    foreach (var prop in props){
         var valueProp = prop.PropertyType.GetProperty("Value");
         modelbuilder.GetEntity(type)
            .Property(valueProp)
            .HasColumnName(prop.Name)
    }
}

Can this be done?





Aucun commentaire:

Enregistrer un commentaire