簡體   English   中英

在AccountContext中添加新屬性,EF Code First?

[英]Adding new properties in AccountContext, EF Code First?

在POC應用程序中,我已經開始使用默認的MVC-4互聯網應用程序模板。 我在AccountContext添加了更多屬性:

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);
    }

我看到實體框架忽略了在數據庫中創建Employee&Work實體。 在此輸入圖像描述

因此在執行db.SaveChanges();出現以下錯誤db.SaveChanges();

無效的對象名稱'dbo.Employees'

可能是什么問題 ?

您可以將Entity Framework設置為以下內容:

CreateDatabaseIfNotExists<TContext>
DropCreateDatabaseAlways<TContext>

我個人使用CreateDatabaseIfNotExists,如下所示:

public class ContextInitializer : CreateDatabaseIfNotExists<Context>
{
    protected override void Seed(Context ctx)
    {
         // any seed data

    } 

}

在發生這種情況之后,確保Initilizer成員身份,在Global.asax中的某處或在那里調用的靜態函數:

我通常使用這樣的東西:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterAuth();
    AutoMapperConfig.RegisterConfig();

    Database.SetInitializer(new ContextInitializer());

    using (var context = new Context())
    {
        context.Database.Initialize(false);
    }

    if (!WebSecurity.Initialized)
    {
        WebSecurity.InitializeDatabaseConnection(
            connectionStringName: "DefaultConnection", 
            userTableName: "User", 
            userIdColumn: "Id", 
            userNameColumn: "Email", 
            autoCreateTables: false);
    }
}

如果您計划不斷添加,刪除實體中的屬性並添加新屬性,您可能需要查找可以為您更新數據庫的Code First遷移。

點擊這里了解更多〜Code First Migrations

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM