简体   繁体   中英

Entity Framework Core 2 - Code first not creating tables

Entity Framework Core 2.0 has been recently released and i am using it.

I have added the following line in method ConfigurationServices() in file Startup.cs (My connectionstring is fine).

services.AddDbContext<AutoPartsContext>(options => 
options.UseSqlServer(Configuration.GetConnectionString("NetCore")));

and in Configure method,

using (var serviceScope = 
app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = 
serviceScope.ServiceProvider.GetRequiredService<MyConntectionStringName>();
context.Database.Migrate();
context.Database.EnsureCreated();
}

This is creating the database but not tables. When i call a simple count on my tables,

var a = _context.Users.Count();

It throws following exception

Invalid object name 'Users'. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

However, if i create table manually, everything works perfectly. I need all tables to be auto created.

EF Core version: 2.0, Database Provider: Microsoft.EntityFrameworkCore.SqlServer, Operating system: Windows 10, IDE: Visual Studio 2017 Preview 2

You need to use migrations for this, as database initializers that used to exist in pre-Core EF are no longer available.

Please refer to Migrations - EF Core with ASP.NET Core MVC tutorial .

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