Mohsin
Mohsin

Reputation: 732

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

Upvotes: 5

Views: 13227

Answers (1)

Ricardo Peres
Ricardo Peres

Reputation: 14535

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.

Upvotes: 7

Related Questions