Create a table dynamically in DbContext using C# EF 4.1.

c# dbcontext entity-framework


I want to add tables to a SQLCe database at runtime, since the tablenames are not static and known at compile time. I try to do this with Entity Framework 4.1 and DbContext as follows:

public class PersonContext : DbContext
    public PersonContext()
        : base("UnicornsCEDatabase")
public class Person
    public int NameId { get; set; }
    public string Name { get; set; }
public class Program
    static void Main(string[] args)
        using (var db = new PersonContext())

            //Try to create table
            DbSet per = db.Set<Person>();
            var per1 = new Person { NameId = 1, Name = "James"};
            int recordsAffected = db.SaveChanges();

                "Saved {0} entities to the database, press any key to exit.",

When trying to run this it throws this error: The entity type Person is not part of the model for the current context.

Is it possible to add a DbSet at runtime to the DbContext without having to define that DbSet(with its schema) in the database?

When defining the DbContext statically with Person, EF will create the entire database and the tables on the fly, which is great.

For example:

foreach (var item in collection)
   string tableName = "PersonTable_"+item.Name;
   //Add a table with the name tableName to DbContext

Is this somehow possible with EF or do I have to create these with some other technique?

Thanks, Juergen

11/15/2011 2:40:19 PM

Popular Answer

you could use following, it would create tables or update them as necessary, not sure if this would work in production since it drops the db when model changes

                new DropCreateDatabaseIfModelChanges<DataContext>());

or if could create your own implementation of System.Data.Entity.IDatabaseInitializer interface

11/15/2011 4:03:50 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow