BendEg
BendEg

Reputation: 21108

Distribute entity framework models over different assemblies

Currently i am trying to use entity framework 6.3 with a kind of distributed models. My problem is, i want to seperate the models in different assemblies (for example the core application and plugins).

Now i'm search for a way, that my application get all models over reflection or some thing similar and register all models in the ef db context before startup.

Is this possible with entity framework 6?

Thank you.

Upvotes: 4

Views: 1198

Answers (1)

bateloche
bateloche

Reputation: 709

You can search for your models in every assembly over reflection.

Iterate through the AppDomain's assemblies and search for an attribute, interface or base class, see an example below.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");

    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
    {
      var entityTypes = assembly
        .GetTypes()
        .Where(t =>
          t.GetCustomAttributes(typeof(PersistentAttribute), inherit: true)
          .Any());

      foreach (var type in entityTypes)
      {
        entityMethod.MakeGenericMethod(type)
          .Invoke(modelBuilder, new object[] { });
      }
    }
}

Upvotes: 5

Related Questions