【发布时间】:2017-11-04 09:58:28
【问题描述】:
我是 Entity Framework 的新手,在 DB 中创建表时遇到问题。
数据库创建得很好,但它没有从实体创建表。
这是我的上下文:
public class MyContext : DbContext
{
public MyContext(DbContextOptions<MyContext> options) : base(options) { }
public MyContext()
{
}
public DbSet<User> Users { get; set; }
}
这里是User实体
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string UsernaName {get; set;}
}
这是我在 Startup.cs 中的代码
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<MyContext>();
context.Database.Migrate();
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServiceAuthentication();
services.AddDbContext<MyContext>(options => options.UseSqlite(Configuration.GetConnectionString("SqlLiteConnection")));
services.AddMvc();
}
Migrate create database context.Database.Migrate(); 从文档中我很清楚,但我就是不知道如何从实体创建表。
感谢您的帮助。
不确定是否重要,我的课程 MyContext 是在 Class Libarry 项目中定义的,而不是在 Web 项目中
编辑:
从@borisdj 的回答我发现我必须从包管理器运行这个命令:
添加迁移 MyFirstMigration -Context MyContext -Project MyProject.Db
但我收到此错误:
没有为此 DbContext 配置数据库提供程序。可以通过重写 DbContext.OnConfiguring 方法或在应用程序服务提供者上使用 AddDbContext 来配置提供者。如果使用了 AddDbContext,那么还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象并将其传递给 DbContext 的基本构造函数。
如您所见,我没有覆盖DbContext.OnConfiguring,但我在Startup.cs 中使用AddDbContext,正如您在上面看到的那样,并且具有接受DbContextOptions<TContext> 对象的构造函数,但我仍然收到此错误。
可能是因为MyContext 是在类库项目中定义的,而不是在 Web 项目中(Startup.cs 所在的位置)
【问题讨论】:
标签: c# entity-framework asp.net-core entity-framework-core