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

c# dbcontext entity-framework


Since the tablenames are not static and known at build time, I want to add tables to a SQLCe database during runtime. With Entity Framework 4.1 and DbContext, I attempt to do the following:

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.",

This fails to execute when attempted with the following error: The model for the current context does not include the entity type Person..

Is it feasible to create a DbSet (together with its schema) in the database and then add it to the DbContext without at runtime?

It's fantastic that EF will automatically generate the complete database and the tables when the DbContext is defined statically with Person.

For instance:

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

Is this at all doable with EF, or do I need to use some other method to make these?

Thanks, Juergen

11/15/2011 2:40:19 PM

Popular Answer

You could use the following; however, because it loses the database when the model is changed, it's unclear if it will function in a production setting.

                new DropCreateDatabaseIfModelChanges<DataContext>());

or if you were able to develop your own System implementation. interface Data.Entity.IDatabaseInitializer

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