0
在POC應用程序中,我已經開始使用默認的MVC-4互聯網應用程序模板。 我在AccountContext
增加幾個特性:在AccountContext,EF Code First中添加新屬性?
public class AccountsContext : DbContext
{
public AccountsContext()
: base("vs12localdb")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<Employee> Employees{ get; set; }
public DbSet<Work> DailyWorks { get; set; }
}
但是,試圖在HttpPost方法中添加Employee
實體時:
[HttpPost]
public ActionResult Create(EmployeeViewModel emp)
{
if (ModelState.IsValid)
{
emp.UserId = WebSecurity.HasUserId ? WebSecurity.CurrentUserId : -1;
db.Employees.Add(emp);
db.SaveChanges(); //Causing Error: Invalid object name 'dbo.Employees'.
return RedirectToAction("Index");
}
return View(emp);
}
我看到實體框架忽略數據庫中創建員工&實體機構開展工作。
因此得到下面的錯誤,而這樣做db.SaveChanges();
:
無效的對象名稱dbo.Employees「
可能是什麼問題?
什麼是'ContextInitializer'在此行中,Database.SetInitializer(新ContextInitializer()); – Abhijeet 2013-03-17 13:30:29
我之前定義的公共類ContextInitializer,它告訴數據庫我用實體框架指定的配置。 取自文檔: 獲取或設置數據庫初始化策略。當System.Data.Entity.DbContext實例從System.Data.Entity.Infrastructure.DbCompiledModel初始化時,將調用數據庫初始化策略。該策略可以選擇檢查數據庫是否存在,創建新的數據庫,併爲數據庫創建數據。默認策略是System.Data.Entity.CreateDatabaseIfNotExists的實例。 –
2013-03-17 13:31:52