我有Dbset和创建这样的数据库。当第一次创建db时,当我在dbset中添加列之后,则迁移不起作用,未找到表列。请告诉我如何在Xamarin表单中启用EF Core Sqlite迁移。
public BaseSQLRespository(string databasePath)
{
try
{
_databasePath = databasePath;
Database.EnsureCreated();
// bool IsDatabaseCreated= ;
// Settings.IsDatabaseCreatedSettings = IsDatabaseCreated;
}
catch (Exception ex)
{
throw ex;
}
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
try
{
optionsBuilder.UseSqlite(string.Format("Filename={0}", _databasePath));
}
catch (Exception ex)
{
throw ex;
}
}发布于 2019-07-23 13:49:21
假设您使用add-migration命令为新列创建了迁移,您可以通过调用Migrate()方法而不是EnsureCreated()在运行时启用迁移的执行。该方法的文档可以在here中找到。
根据微软的文档,Migrate方法与EnsureCreated方法不兼容,后者在创建数据库模式时实际上绕过了迁移-因此在您的情况下,您必须在尝试新代码之前删除旧数据库(卸载应用程序或清除其数据)。
不要在调用
Migrate()之前调用EnsureCreated()。EnsureCreated()绕过了创建模式的迁移,这会导致Migrate()失败。
发布于 2019-07-23 05:49:03
要添加初始迁移,请运行以下命令:
dotnet ef migrations add YourNameOfMigration接下来,将迁移应用于数据库以创建模式:
dotnet ef database update每次向模型添加新字段时,都应该添加迁移并将其应用于DB。
发布于 2019-07-23 14:04:45
我猜你的配置是错误的,你不应该在ctor中调用Database.EnsureCreated();,因为OnConfiguring()还没有被调用,你的数据库也没有初始化。
您可以创建一个在serviceProvider启动后调用的方法。
public static void Initialize(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetRequiredService<BaseSQLRespository>();//use your service provider any thing which you can get your current created `BaseSQLRespository`
context.Database.EnsureCreated();//once call when your app is started. (it is up to you which method you used to call)
...
...
}除了,这里有相似的主题和不同的解决方案,你可以查看:Error in Database.EnsureCreated() while using Entity Framework with Sqlite in Xamarin
https://stackoverflow.com/questions/57145233
复制相似问题