Entity structure code does not first create tables using VS 2012

I have an MVC4 Web api project under visual studio 2012 for which I would like to first create and manage a database using EF 6.0.2. In fact, the solution entails four projects:

  • OnlineShop.Application (User Interface)
  • OnlineShop.Model dedicated to POCO classes only
  • OnlineShop.Test for unit tests and
  • OnlineShop.Core having UnitOfWork, GenericRepository and DatabaseContext Classes

Each of the projects mentioned includes app.config, which contains the same connections as web.config.

Problem: After starting the project (in debug mode), the database is created as shown on the server explorer (in visual studio 2012). But he has no tables !!!

The database context class also looks like this:

 public class DatabaseContext : DbContext
{
    public DatabaseContext() : base("OnlineShopDb")
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, Configuration>());
    }

    //public static void InitializeDatabase()
    //{
    //    using (var context = new DatabaseContext())
    //    {
    //        context.Database.CreateIfNotExists();
    //        Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, Configuration>());
    //    }
    //}

    public DbSet<Person> Persons { get; set; }
    public DbSet<Customer> Customers { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Audit> Audits { get; set; }
    public DbSet<RoleGroup> RoleGroups { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<UserInRole> UserInRoles { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<OrderDetail> OrderDetails { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<ProductCategory> ProductCategories { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Entity<Person>().Map<User>(c => c.Requires("Discriminator").HasValue("User"));
    }
}

I surfed the Internet so much, found a lot of articles and samples regarding the first approach to the EF code, but, unfortunately, I could not deal with this bad problem!

I would appreciate it if someone could help me with this.

+4
source share
1 answer

Entity Framework code does not first create your database until you try to access it, so run the project and try to get or insert some record into your database.

Another good tip: if you change your models, EF will throw exeption by default, and you will have to drop the current database so that EF can create a new file.

+7

Source: https://habr.com/ru/post/1527954/


All Articles