C# EF 4.1 Create table dynamically within DbContext

一笑奈何 提交于 2019-11-29 11:17:43

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

 Database.SetInitializer<DataContext>(
                new DropCreateDatabaseIfModelChanges<DataContext>());

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

Tourki

Entity Framework does not support dynamic creation of tables. So if you're using Code-First you have to define your DbSets in your DbContext in order to create corresponding tables.

http://entityframework.codeplex.com/discussions/448452

There are some workarounds out there like this question

Entity Framework (Code First) - Dynamically Building a Model

But EF is not the best ORM for that, try ServiceStack.OrmLite (it's a lightweight ORM).

user3467452
namespace ConsoleApplication31
{
    public class PersonContext : DbContext
    {
        public PersonContext()  : base("UnicornsCEDatabase")
        {
        }
        public DbSet<Person> Persons { get; set; }
    }
    public class Person
    {
        public int PersonId { get; set; }
        public int NameId { get; set; }
        public string Name { get; set; }
    }

    public class Program
        {
            static void Main(string[] args)
            {
                using (var db = new PersonContext())
                {
                    db.Database.Delete();

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

                    Console.WriteLine(
                        "Saved {0} entities to the database, press any key to exit.",
                        recordsAffected);
                    Console.ReadKey();
                }
            }
        }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!