mattinsalto
mattinsalto

Reputation: 2366

Adding new models to an existing context at runtime in entity framework

Is it posible to have a dbContext in a dll, import it in another project and add new models/entities/tables programatically so you can make joins with previously existing tables?

I'll try to explain why I want such a thing (may be there is a better way).

I want to make a modular app, so there will be a Core.dll with a dbContext. And I want others making modules, to be able to extend the Core dbContext.

Thanks.

Upvotes: 0

Views: 1559

Answers (1)

ssis_ssiSucks
ssis_ssiSucks

Reputation: 1506

Sounds like you basically want to do what EF already does, if I'm understanding correctly. There's at least a couple ways to do this using code first. I like using the EntityTypeConfiguration approach (rather than fluent API) to build up my object model. In your case, that might look something like this:

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using CoreNamespace;

namespace CoreNamespace
{
   public class MyDbContext:DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
        modelBuilder.Configurations.Add(new CoreEntityConfiguration());
    }
}

public class CoreEntity
{
    //list properties, methods, etc
}

public class CoreEntityConfiguration : EntityTypeConfiguration<CoreEntity>
{
    public CoreEntityConfiguration()
    {
        //configure entity and map to db
    }
}

namespace ExtendingProjectNamespace
{
    public class MyExtendedDbContext : MyDbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Configurations.Add(new SubEntityConfiguration());
         }
    }

    public class SubEntity
    {
        //list properties, methods, etc
    }

    public class SubEntityConfiguration : EntityTypeConfiguration<SubEntity>
    {
        public SubEntityConfiguration()
        {
            //configure entity and map to db
        }
    }
}

The namespaces here are intended to refer to separate projects/dlls

Upvotes: 1

Related Questions