简体   繁体   English

实体框架核心2-代码首先不创建表

[英]Entity Framework Core 2 - Code first not creating tables

Entity Framework Core 2.0 has been recently released and i am using it. Entity Framework Core 2.0 最近发布 ,我正在使用它。

I have added the following line in method ConfigurationServices() in file Startup.cs (My connectionstring is fine). 我在文件Startup.cs中的ConfigurationServices()方法中添加了以下行(我的连接字符串很好)。

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) 在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔值breakConnection,动作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 EF核心版本:2.0,数据库提供程序:Microsoft.EntityFrameworkCore.SqlServer,操作系统: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. 您需要为此使用迁移,因为以前在EF核心之前存在的数据库初始化程序不再可用。

Please refer to Migrations - EF Core with ASP.NET Core MVC tutorial . 请参考Migrations-EF Core with ASP.NET Core MVC教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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