Entity Framework Core 2.0 Dynamically Creating A Database - entity-framework-core

I am new to EF Core, and as I tried using it I found out that you need to add migrations for it to create a database from models. My question is, do we have another option aside from migrations to dynamically create the database on run time just like what it was in EF 6?
Thanks.

Until a seeding mechanism is provided in EF Core you can provide your own seeding mechanism.
In earlier phases of a project, when the database is not yet fixed, I don't care that data get lost. When I want to recreate the database dynamically I call the function below. By the setting of a parameter I determine if this "recreateDatabase"-function is called yes or no. The function is included in MyOwnDbContext class.
The seed function you need to write is very similar to the one you use in EF 6.
private static void recreateDatabase(YourOwnDbContext dbContext)
{
dbContext.Database.EnsureDeleted();
dbContext.Database.EnsureCreated();
seed(dbContext);
}

Related

Is there a way to query the database before or during OnModelCreating?

Inside of OnModelCreating, I want to be able to ignore a column if the database is on an older migration EF Core 5 throws an exception if I attempt to read from the database directly, or indirectly by querying the applied migrations. I'm not certian that it's even a good idea, since OnModelCreating is used during the migration 😩, but I'll burn that bridge when I cross it.
There are some examples on how one would do this with EF6, but they don't seem to apply anymore with EF Core.
While Ivan Stoev is right that --generally-- you should model the target database without outside input, the real world isn't always that clear-cut. In my particular case, there are multiple service instances (Azure Functions) that need to read and write to a single database. In order to maintain zero downtime, those Functions need to not read or write columns that don't yet exist.
I solved the problem the way Serge suggested. The database has a known version, populated with seed data that increments with every migration. On startup, the service reads that version with a regular old Microsoft.Data.Sql.SqlConnection. This version is then added to the IServiceCollection as a singleton to be used by the DbContext constructor.
When talking to an older database version, OnModelCreating does things like this:
builder.Entity<Widget>(w =>
{
// another option would be to use the migrations table instead of an integer
if (DatabaseVersion < ContextVersions.WidgetNewPropertyAddedVersion)
{
w.Ignore(w => w.NewProperty);
}
else
{
w.Property(w => w.NewProperty)
.HasDefaultValue(0);
}
});
The startup code also detects if it's been started by the Entity Framework tools and does not read the database version, instead assuming "latest". This way, we do not ignore new properties when building the migration.
Figuring out how to let the service instances know that the database has been upgraded and they should restart to get the new database model is an exercise left up to the reader. :)

Entity Framework Migrations with a different Database

I am stuck trying to figure out how to set the database to run a migration on.
I have created a new empty project and set up Entity Framework using code first. I have all my classes built.
I want to add a new database and run the migrations on this. I have Migrations working but I can't figure out what database they are running on.
Is it possible to set the database you want to use for the migrations?
Multiple DBs for the same context gets a little tricky. But It is possible:
The essence of the problem is how EF decides which connection to use.
It will access instantiate the context without NO PARAMS during migration.
So depending on how that behaves influences you outcome and success.
Start here:
EntityFramework code-first custom connection string and migrations

Where the CREATE DATABASE statement is generated in Entity Framework Code First with Migrations?

I need to configure the database created by Entity Framework Code First MigrateDatabaseToLatestVersion class.
Is it possible to influence the database files parameters like size or maxsize? What interests me in particular, is there a way to add database files?
I assume I need to find the moment where the Entity Framework generates the CREATE DATABASE statement and influence it a bit. As far as I understand, the SqlServerMigrationSqlGenerator class is too late because the database already exists at this point.
Edit: According to comment this doesn't work:
You can just add code based migration using Add-Migration command and modify its Up method to execute Sql("ALTER DATABASE ...") and do what ever you want with your database.
Database is created through DbProviderServices - that is a bridging component between EF and specific database server. ObjectContext exposes operations for creating database and generating database creation script. DbMigrator use database creation operation when you execute Update. It checks that if Database exists and if not it uses ObjectContext.CreateDatabase. So if you want to change the process of creating the database you need to implement your own implementation of the migrator to change the way how Update method generates the database (maybe you just need a decorator which will create a database prior to executing DbMigrator.Update operation).

EF CodeFirst - Create index after database create

I'm migrating my project from database-first to code-first.
Entity Framework does some nice work creating my new database (that should mimic the old one).
I'm using a combination of data annotations and the fluent API to describe my tables.
My database has a few indexes and I would like Entity Framework to create them as well. It seems the old way to do this is to define your own Initializer and use custom T-SQL.
But now that we have EF Migrations it should be easier to do so.
I can't seem to figure out how to combine CreateDatabaseIfNotExists<> with an automatic migration to create the indexes. I've tried to use the MigrateDatabaseToLatestVersion<,> but it doesn't seem to perform the migration after the Database has been created.
What is the proper way to create indexes and constraints on database creation now that we have Entity Framework 4.3?
Don't use CreateDatabaseIfNotExists if you want to use migrations. Use MigrateDatabaseToLatestVersion from the beginning - it will create your database as well. Put your index creation code (calls to CreateIndex) into Up method of your migration class.
If you already have existing database and you want to use migrations you must first create initial migration.

Manually editing database in code first entity framework

I have been trying out EF 4.1 (code first) with MVC 3. I am thinking ahead to when the application will need changes. I tested a couple of scenarios. I like the idea of manually editing the database when the model (my POCOs) would changed.
ASP.NET error when I change the model :
"The model backing the 'CTCMContext' context has changed since the database was created. Either manually delete/update the database..."
Now, it says that I can "manually update the database", but I did and still get the same error. Am I missing something !!?!
EDIT
Does this have to do with the model hash generate by EF ?
I have had some struggles with this as well. I found that when you let EF create your database for you that a table named dbo.EdmMetadata is created and this is where/how EF tracks the state of the model. I found that if you delete this table after the database has been initially created you will put things into "manual mode" where you can now manually add/remove columns, tables, etc. from your database and EF will not throw the error that you are seeing.
If however you want to keep having EF update your database as you make changes to your model, you will need to create and call a ContextInitializer class that inherits from either DropCreateDatabaseIfModelChanges or DropCreateDatabaseAlways depending upon the behavior that you want to have happen.
change the class with the new fieldnames, delete the table "EdmMetaData" then recompile your app.
You will be responsible on modifying the fieldname on your views.
it works for me.
As I can see, there aren't really any methods built-in EF for code-first data evolution.
For what was of my initial question, the answer lies in removing the schema generation/validation. It is only then that manually editing the code and database may work.
UPDATE :
EF 5.0 now support migrations
I know this has been marked as solved but in my case it didn't do the trick.
Once I deleted dbo.EdmMetadata I was getting a different error:
Model compatibility cannot be checked because the database does not contain model metadata. Ensure that IncludeMetadataConvention has been added to the DbModelBuilder conventions.
The way it worked for me was to remove the Initializer class from Application_Start:
void Application_Start(object sender, EventArgs e)
{
// MyDB.SetInitializer<MyContext>(new MyInitializer());
}