代码优先:创建表而不是数据库

时间:2013-10-14 21:14:34

标签: c# entity-framework ef-code-first

我已准备好我的模型代码优先EF ,我在 sql express 工作上尝试。但我在将其转换为 sql server 时遇到问题:我没有权限重新创建数据库我只能将表添加到空数据库

我已经看到this answer 但是当我试图复制它时,我对上下文部分有一些麻烦:

public class DropCreateDatabaseTables : IDatabaseInitializer<Context> {

#region IDatabaseInitializer<Context> Members



public void InitializeDatabase(Context context)

我已经将引用放到了System.Data.Entity但是没有用,并且Context类不是System.Runtime.Remoting.Contexts上引用的

代码有问题吗?或者使用EF的最后一个工具是一个更好的解决方案吗?

修改

最后是:

的DbContext:

public class PeopleContext: DbContext
{
    public DbSet<Person> People { get; set; }
    public DbSet<Adress> Adresses{ get; set; }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Add Entity type configuration classes
        modelBuilder.Configurations.Add(new PersonConfiguration());
        modelBuilder.Configurations.Add(new AdressConfiguration());

    }
}

初​​始化器:

  public class DropCreateDatabaseTables : IDatabaseInitializer<PeopleContext>
{

    public void InitializeDatabase(PeopleContextContext)
    {

      bool dbExists;

      using (new TransactionScope(TransactionScopeOption.Suppress))

      {

        dbExists = Context.Database.Exists();

      }

      if (dbExists)

      {       

        // remove all tables
          Context.Database.ExecuteSqlCommand("EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'");
          Context.Database.ExecuteSqlCommand("EXEC sp_MSforeachtable @command1 = \"DROP TABLE ?\"");



        // create all tables

        var dbCreationScript = ((IObjectContextAdapter)Context).ObjectContext.CreateDatabaseScript();

        Context.Database.ExecuteSqlCommand(dbCreationScript);


        Context.SaveChanges();

      }

      else

      {

          throw new ApplicationException("No database instance");

      }

    }
}

呼叫:

class Program
{
    static void Main(string[] args)
    {
        var person= new Person
        {
            Identifier= "John Doe"
        };
        Database.SetInitializer(new DropCreateDatabaseTables());
        using (var context = new PeopleContext())
        {
            context.People.Add(person);
            context.SaveChanges();


        }
    }
}

感谢Lukas Kabrt!

1 个答案:

答案 0 :(得分:3)

示例中的Context类应该是您的DbContext类,即您指定DbSet<>的类。

示例:

DbContext类

public class DataContext : DbContext {
    public DbSet<Customer> Customers { get; set; }
}

<强> DatabaseInitializer

public class DropCreateDatabaseTables : IDatabaseInitializer<DataContext> {
    ...
}