简体   繁体   中英

Adding new properties in AccountContext, EF Code First?

In a POC application I have started with default MVC-4 internet application template. I have added few more properties in 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; }
}

But when trying to add Employee entity in the HttpPost method :

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

I see entity framework ignoring to create Employee & Work entities in the database. 在此输入图像描述

Thus getting following error, while doing db.SaveChanges(); :

Invalid object name 'dbo.Employees'

What could be the issue ?

You can set Entity Framework to the following:

CreateDatabaseIfNotExists<TContext>
DropCreateDatabaseAlways<TContext>

I personally use CreateDatabaseIfNotExists like so:

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

    } 

}

Just make sure you Initilizer the Membership after this takes place, somewhere in Global.asax or a static function called there:

I generally use something like this:

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

If you plan on continuously adding, removing properties from Entities and adding new ones, you may want to look up Code First migrations which can handle updating the Database for you.

Click here for more ~ Code First Migrations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM