2

I'm new to MVC and the EF. My app is a simple code-first with several POCO classes and a DBContext like this:

   public class ExpDefContext : DbContext
   {
      public DbSet<Experiment> Experiments { get; set; }
      public DbSet<Research> Researches { get; set; }
      ...

The problem: I need to add to my data model an entity-set that its type is built at runtime from user input, meaning I have no idea of its data structure.

I read the non-generic Dbset class is made just for this, so I added to the context:

    public DbSet Log { get; set; }

...and created a constructor for the context that accepts the runtime-type and sets the new Dbset:

        public ExpDefContext(Type LogRecType)
        {
            Log = Set(LogRecType);
        }

(the type by the way is built using Reflection.Emit).

In the controller I create the type (named LogRec) and pass it to a new DBContext instance. Then I create a LogRec instance and try to Add it to the database:

    Type LogRec;
    LogRec = LogTypeBuilder.Build(dbExpDef, _experimentID);
    var dbLog = new ExpDefContext(LogRec);
    var testRec = LogRec.GetConstructor(Type.EmptyTypes).Invoke(Type.EmptyTypes);
    dbLog.Log.Add(testRec);
    dbLog.SaveChanges();

and I get an exception from the dbLog.Log.Add(testRec):

The entity type LogRec is not part of the model for the current context

What am I doing wrong? Is there a better way to do this (preferably without diving too deep into the Entity Framework)?

Thanks

user1707621
  • 95
  • 1
  • 2
  • 9

1 Answers1

4

I suspect that EF only reflects over the generic DbSet<T> properties in your derived DbContext and ignores any non-generic DbSet properties when the model is created in memory.

However, an alternative approach might be to use the Fluent API in OnModelCreating to add your dynamic type as an entity to the model.

First of all you can add a type to the model only when the model is built in memory for the first time your AppDomain is loaded. (A model is built only once per AppDomain.) If you had a default constructor of the context in addition to the overloaded constructor and had created and used a context instance using this default constructor your model would have been built with only the static types and you can't use the dynamic type as entity anymore as long as the AppDomain lives. It would result in exactly the exception you have.

Another point to consider is the creation of the database schema. If your type is unknown at compile time the database schema is unknown at compile time. If the model changes due to a new type on the next run of your application you will need to update the database schema somehow, either by recreating the database from scratch or by defining a custom database initializer that only deletes the LogRec table and creates a new table according to the new layout of the LogRec type. Or maybe Code-First Migrations might help.

About the possible solution with Fluent API:

Remove the DbSet and add a Type member instead to the context and override OnModelCreating:

public class ExpDefContext : DbContext
{
    private readonly Type _logRecType;

    public ExpDefContext(Type LogRecType)
    {
        _logRecType = LogRecType;
    }

    public DbSet<Experiment> Experiments { get; set; }
    public DbSet<Research> Researches { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
        entityMethod.MakeGenericMethod(_logRecType)
            .Invoke(modelBuilder, new object[] { });
    }        
}

DbModelBuilder doesn't have a non-generic Entity method, hence dynamic invocation of the generic Entity<T> method is necessary.

The above code in OnModelCreating is the dynamic counterpart of...

modelBuilder.Entity<LogRec>();

...which would be used with a static LogRec type and that just makes the type as entity known to EF. It is exactly the same as adding a DbSet<LogRec> property to the context class.

You should be able to access the entity set of the dynamic entity by using...

context.Set(LogRecType)

...which will return a non-generic DbSet.

I have no clue if that will work and didn't test it but the idea is from Rowan Miller, member of the EF team, so I have some hope it will.

Slauma
  • 175,098
  • 59
  • 401
  • 420
  • thanks very much. I saw Rowan Miller's suggestion before but you put it in the right context, so to speak. You were also right about my code having a default constructor and the model been built before calling the parametrized one. I don't know how to overcome this, since my dynamic type is dependent on a value from Experiments Dbset. It like building the model in steps: first Experiments, user select a value to decide the type, then the non-generic LogRec. Any suggestions, leads? – user1707621 Sep 30 '12 at 07:01
  • @user1707621: I have two ideas you could try: 1) `context.Database.Initialize(true);`: The parameter `true` is "force" initialization. I am not sure if this will recreate the model in memory or only run the DB intializer again (look at the description in intellisense). 2) You could try to work with two different context classes, one without the `LogRecType` and one with it. Two context classes should result in two models in memory. This is all pretty difficult and advanced stuff. I suggest that you just create new questions if you get stuck. – Slauma Sep 30 '12 at 11:58