我已經準備好我的模型上代碼第一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!
不要寫你自己的初始化啓動,但使用標準的,如' Database.SetInitializer(新的DropCreateDatabaseAlwa ys());'查看[DropCreateDatabaseAlways](http://msdn.microsoft.com/en-us/library/gg679506%28v=vs.103%29.aspx)。 –
因爲我的憑證我不能刪除數據庫並重新創建它我只能在現有的空數據庫上創建表格 – rlartiga