我是實體框架的新成員,並且在創建DB中的表時遇到問題。Microsoft.EntityFrameworkCore.Sqlite(2.0.0 peview1-final)遷移不會創建表
數據庫創建正常,但不會從實體創建表。
這裏是我的上下文:
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();
}
遷移創建數據庫的代碼context.Database.Migrate();
從文檔中我很清楚,但我只是不能如何從實體創建表格。
感謝您的任何幫助。
而且不知道這是很重要的,我MyContext
類類Libarry項目的定義,而不是在Web項目
編輯:
從@borisdj答案,我想通了,我要運行這個從程序包管理器命令:
附加遷移MyFirstMigration -Context MyContext -Project MyProject.Db
但我收到此錯誤:
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
正如你看到的,我不重寫DbContext.OnConfiguring
但我在使用Startup.cs
作爲AddDbContext
你可以在上面看到,並有構造函數接受DbContextOptions<TContext>
對象,但我仍然得到這個錯誤。
是不是可能是因爲MyContext
在類庫項目,而不是在Web項目(其中Startup.cs是)
:術語「創建遷移」沒有被識別爲cmdlet的名稱.... 。我正在運行Microsoft.EntityFrameworkCore.Sqlite 2.0(它是預覽版)和VS 2017 – carpics
我的不好,它是'添加遷移' – borisdj
很好的添加遷移初步幫助。只是我有錯誤,我有更多的一個DbContext,所以我不得不指定DbContex像添加遷移初始-Context MyContext。如果您擁有多於一個DbContext,並且我會接受您的答案,請更新您的答案。謝謝 – carpics