Entity Framework apply migrations at runtime - c#

i'm creating a C# WinForms application which uses Entity Framework Code First and it is set to create the database if it doesn't exists.
Since the app is not distributed with a database, it creates it when it's needed, so i need to find a way to detect which migrations need to be applied for each case when i release a new version of the app.
How can i detect and apply needed migrations at runtime?

try this Initializer:System.Data.Entity.MigrateDatabaseToLatestVersion,it will update your database(no delete db,no delete data),just update entity changed.
Database.SetInitializer(new MigrateDatabaseToLatestVersion<T, DbMigrationsConfiguration<T>>());
try
{
using (var ctx = new T())
{
ctx.Database.Initialize(true);
}
}
catch (Exception e)
{
}

Related

Microsoft.EntityFrameworkCore.SqlServer - Database not updating on context.Database.Migrate();

I'm trying to move a project from using Dapper to Microsoft.EntityFrameworkCore.SqlServer.
I've created the entities and their respective mappings(configurations).
Also I'm running in my ConfigureServices method inside startup.
using var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope();
using var context = scope.ServiceProvider.GetRequiredService<SpannerContext>();
context.Database.EnsureCreated();
context.Database.Migrate();
But nothing is happening;
Logs shows:
info: Microsoft.EntityFrameworkCore.Migrations[20405]
No migrations were applied. The database is already up to date.
But I've added some new DbSets and also change some column types
Am I missing something?
try to generate your models and configuration form an existing database, then apply the modifications/changes in your models.
https://www.entityframeworktutorial.net/efcore/create-model-for-existing-database-in-ef-core.aspx
I order to solve the problem i followed the following steps
Scaffold the database;
Add a migration;
Run the code for the first time, to ensure the entity framework migrations table is created;
Go to the entity framework table and add the name of the create migration;
Modify the database with the new tables/columns e etc;
Add a new migration;
The new migration should work as expected;
This way you don't need to comment the up part of the code;

Xamarin Entity Framework Migration - Table 'name' already exists

So, I have a Xamarin app with a local DB, and I'm using the command this.Database.Migrate() to apply any pending migration, it works fine at first, but the problem is, when I uninstall the app and install again, the app try to execute the same pending migration, and I got the error "Table 'name' already exists". Is there a way to ignore tables that already exists 'cause I don't want to delete the users local data every time they uninstall the app.
I'm using the command dotnet ef migrations add initial to create migrations.
To everyone facing this problem, I solved creating a method using SQLiteConnection. You need to add using SQLite; :
public static bool TableExists(string tableName)
{
var dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), databaseName);
using (var db = new SQLiteConnection(dbPath))
{
var info = db.GetTableInfo(tableName);
if (info.Any())
{
return true;
}
}
return false;
}

EntityFramework is deleting my records on dbcontext creation

In a .NET Core project I have the following model:
public class WrapperContext : DbContext
{
public DbSet<WrappedFunction> Functions { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseSqlite("Data Source=functions.db");
}
}
public class WrappedFunction
{
[Key]
public int FunctionId { get; set; }
public String FunctionName { get; set; }
public String AssemblyPath { get; set; }
public String FactoryName { get; set; }
}
As you can see it is an Sqlite database.
I have added the initial migration and updated the database. Before running my test application I have populated the Functions table with a single record. I can open the DB with SqliteManager to see the record is there.
I then try to access the DB with the following function:
static MUinfo getInfoFor(String command)
{
UFInfo rv = null;
using (var ctx = new WrapperContext()) // <---- record disappears here
{
foreach (var fn in ctx.Functions)
{
if (fn.FunctionName.Equals(command))
{
rv = new UFInfo()
{
AssemblyPath = fn.AssemblyPath,
FactoryName = fn.FactoryName,
CommandName = command
};
}
}
}
if (rv != null) return rv;
return "No Info for " + command;
}
However, when stepping through the debugger I see that the foreach loop never executes as there are no records in the DB. When I stop before executing the foreach I can verify (using SqliteManager) that my single record has been deleted from the database.
So, it would appear that the DbContext object is somehow deleting the data from the database. Why would that be and what have I done wrong here? I am fairly new to EntityFramework so I may have done something obvious, but it isn't obvious to me.
One additional bit of info here. The project that does the db access is a library project. I have to copy the DB over to the build directory of the application before populating it and running the application. I don't know if that makes a difference or not.
Edit 6/19/17 (18:51):
OK. A bit more information (thanks to #StevePy). Nunit3 seems to conflict with EFCore (though I don't get any errors on restore) so I couldn't create a unit test for this. So I inserted a using (var ctx...) above the one in the listing above and inserted a couple of dummy records. Then I exited that using block and when I entered the one to traverse the records they were there.
However, I then commented out the dummy insertions and reran my test. And, once again, both records disappeared. So there is something very weird going on here with EFCore.
Edit 6/20/17 (15:30):
Well, I'm still not sure what is going on but there is an odd interaction between EFCore and Microsoft.Data.Sqlite.
I decided to remove all references to EFCore and simply use SQL queries on the DB. I did this without recreating the DB (so I was using the one already created by EFCore). I noticed the exact same behavior when I created a new SqliteConnection without using EFCore.
In desperation I deleted the DB and recreated it from scratch using Microsoft.Data.Sqlite. This DB didn't have any of the EFCore information in it, obviously. I then populated the DB with some test records and went to use it. No more disappearing records.
Apparently there was something very strange in the way EFCore set up the database in the first place that caused the issue. But I don't have any idea what it was.
What is likely happening is that you are using CodeFirst /w EF, but taking a DB first approach when it comes to testing your new code. EF tracks schema changes within the database and my guess is that by you creating the table ahead of time it does not know that the schema is vetted, so it drops and recreates it on context start-up.
The fix here should be to create a "stub" test that populates a test record one time using your EF model. From there you should have a table that EF recognizes against that context and accepts. From there you can create test records in whatever editor for testing purposes.
SQLite has several limitations when it comes to schema migration that you probably will want to consider as well. (see: https://learn.microsoft.com/en-us/ef/core/providers/sqlite/limitations)
You might be better off setting up DB first, telling EF how to map to an existing SQLite schema rather than trying to use Code-First as migration is pretty limited for that DB engine.

SchemaUpdate doesn't work

I made changes to the mapping (added a new table, changed some existing ones), started my app and SchemaUpdate didn't do anything and also didn't throw an exception. I checked with pgAdmin and the schema wasn't updated.
if (sessionFactory == null) {
var configuration = new Configuration();
configuration.Configure();
configuration.AddAssembly(typeof(Building).Assembly);
new SchemaUpdate(configuration).Execute(true, true);
sessionFactory = configuration.BuildSessionFactory();
}
How can I make SchemaUpdate work?
Edit: There are also no exceptions stored in the SchemaUpdate Exceptions property.
Edit2: Nhibernate Version v4.0.30319, not using Fluent.
I tried to export the generated SQL, but the Action is never called.
Apparently, SchemaUpdate only does nothing to a table if it exists. So, the only way to update a table using SchemaUpdate is to manually delete it before application startup.

Drop a database using entity framework

I'm trying to remove a database form my application using entity framework.
The code I use is the following:
using (var dbContext = container.Resolve<ApplicationDbContext>())
{
dbContext.Database.Delete();
}
According to msdn this should work but nothing happens.
the dbContext is registered using ContainerControlledLifetimeManager and should be the same instance used to create the DB.
Adding, updating and deleting instances of entity types needs dbContext.SaveChanges() to reflect changes.
However dbContext.Database.Delete() does not need dbContext.SaveChanges().
If you open connection for example from Sql Management Studio to your database and try to dbContext.Database.Delete() then you receive Cannot drop database "dbContext" because it is currently in use. If you restart you sql server, you drop those connections and then retry dbContext.Database.Delete() you successfully drop database.
Last thing is refresh database list in Sql Management Studio in order to see that database is not there any more.
Testing with this code snippet:
using (var dbContext = new dbContext())
{
dbContext.Database.Delete();
}
After #moguzalp and this (MSDN Database.Delete Function), I came with a solution for my case:
using System.Data.Entity;
Database.Delete("connectionStringOrName");
In my case I was trying to Recreate a mssqllocalDb database for test purposes. But whenever I used the same DbContext (or an immediately new one, disposing the first and opening another), it looked like the database was still up when I tried to create it.
Bad Example: (x)
public static void RecreateDatabase(string schemaScript)
{
using (DbContext context = new DbContext("connectionStringName"))
{
context.Database.Delete(); // Delete returns true, but...
Database database = context.Database;
database.Create(); // Database already exists!
database.ExecuteSqlCommand(schemaScript);
}
}
Working example: (/)
public static void RecreateDatabase(string schemaScript)
{
Database.Delete(); // Opens and disposes its own connection
using (DbContext context = new DbContext("connectionStringName")) // New connection
{
Database database = context.Database;
database.Create(); // Works!
database.ExecuteSqlCommand(schemaScript);
}
}
Context: I'm using this on an [AssemblyInitialize] function to test my ModelContexts
All of your changes occurred on local variable dbcontext.
That is final kick > add dbContext.SaveChanges(); at the end of your using block like so:
using (var dbContext = container.Resolve<ApplicationDbContext>())
{
dbContext.Database.Delete();
dbContext.SaveChanges();
}

Categories

Resources