How to update-database Programmatically in EntityFramework Codefirst? - asp.net-mvc

i am writing a simple CMS over ASP.NET MVC framework (for college final project).my problem is with module's data-migration strategy.as each module will update the database schema when it is installed , a database migration mechanism must be implemented in module installation system.ok , data-migration in entity framework is already there (thanks to MS) , but the migration commands run in package manager console.is there any way to run a Data-Migration code Programmatically?
any help is very appreciated.

If you've enabled the automatic migrations in Package Manager Console you can use the following code in an init section of your app (e.g. in SimpleMembershipInitializer):
var migratorConfig = new Migrations.Configuration();
var dbMigrator = new DbMigrator(migratorConfig);
dbMigrator.Update();
Where Migrations.Configuration is the migration configuration class placed in your project into your namespace (YourProjectNamespace.Migrations).
If you use it programmatically you should at first turn off the EF initializer:
Database.SetInitializer<YourDBContext>(null);
The thing is the programmatic update creates a database if it doesn't exist.

This class exposes the EF migrations in code:
System.Data.Entity.MigrateDatabaseToLatestVersion
In EF, migrations work on a whole database though - not modular parts of one.
Just found this class too:
System.Data.Entity.Migrations.DbMigrator

Related

Insert initial values after EF migration

I have an MVC web application with code-first Entity Framework. We install this application in various computers as a local application. I made a migration to upgrade the database (in this case I added a new table), and after running the migration on upgrade, I want to insert initial data to the database so the users will be able to add/edit/delete them but I don't want the table to be empty at the first time.
Is there a way to do it automatically on upgrade without running a SQL script manually?
Migration class has up method,you can override it and insert/update records using SQL :
public override void Up() {
AddColumn("dbo.Posts", "Abstract", c => c.String());
Sql("UPDATE dbo.Posts SET Abstract = LEFT(Content, 100) WHERE Abstract IS NULL");
}
(Source)
Yes there is. You essentially write a class to conditionally check and insert values, and then you link this class to your entity framework database initialiser. It runs each time there is a migration to be performed, but I think you can change exactly when it runs (e.g. Application startup).
This link will give you the rough idea:
Entity Framework Inserting Initial Data On Rebuild
I have an exact code sample on my PC but I won't be on it until tomorrow. If this link doesn't quite do what you want, I can send you some code tomorrow which definitely will.

How to get current migration name via code

Is there a way for code in my ASP.NET MVC 4, code-first EF app to retrieve the current migration name? I want to display the migration name on an administrator's status page just as a sanity check to verify that the expected migration(s) have been applied.
You can use the DbMigrator (DbMigrator) class for that.
e.g.
var migrator = new DbMigrator(_configuration);
var pending = migrator.GetPendingMigrations();
var all = migrator.GetLocalMigrations();
Where _configuration is your Configuration class under the Migraiton dir.
You need to experiment a bit - see which actually fits your bill.
Also, I'm suggesting that you make an 'initializer' instead of just
adding that into the code. As that's how it's usually done, and a
'natural spot' for those things to happen (you don't 'call it', it
'calls you').
Check this link for an implementation of a custom initializer - which includes some DbMigrator code.
How to create initializer to create and migrate mysql database?

The model backing the 'DMSContext' context has changed

I'm receiving the following error when running my mvc 4 app.
The model backing the 'DMSContext' context has changed since the database was created. Consider using Code First Migrations to update the database
I am running my app against an existing database and do no want to recreate the db each time the model changes.
I've found plenty of answers on google, but none have worked.
Specifically, I've tried adding the following to my global.asax:
Database.SetInitializer<DMSContext>(null);
and
Database.SetInitializer<DMSContext<Contact>>(null);
in the above, DMSContext is the DbContext. Contact is the Model where the change causing the error originates.
I've also tried adding the following to my context class:
public DMSContext() : base()
{
Configuration.AutoDetectChangesEnabled = false;
}
Most of the direction I've followed is from this page, but no luck.
The model backing the <Database> context has changed since the database was created
If you are working with Entity Framework Code First, its recommended that you enable migrations in your application. To do so, see this link.
Now every time you change something in your code (Mostly Entities), just build and then run Update-Database -Force in your Package Manager Console.
Let me know if you have any more questions.
Although you don't use migrations try to create one, do not run it, but you'll be able to see the differences with the database.
Check the name of the class, which inherits the DbContext. It's name have to be the same as the name of the connectionString in Web.config
<connectionStrings>
<add name="TheSameNameAsYourDbContextClass" providerName="" connectionString="" />
</connectionStrings>

Having a Class name "System"

I am creating an MVC project with .NET. A database already exist and I'm using the Entity Framework to access the database.
One of the tables in the database is called "System". EF therefore creates a class by that name. This obviously a conflict with the "System" namespace.
Renaming the table is not practical at this point. Is there another way I can use EF for my project?
Thanks
It's not a problem, you simply need to reference the class through its namespace.
e.g.:
If your generated entity class is under the namespace AppName.EntityModel, the following would work
global::AppName.EntityModel.System
AppName.EntityModel.System
EntityModel.System // if already under the AppName namespace

Understanding VS's ability to create database on first run

I'm working with a (.net4 / mvc3 ) solution file downloaded (from a reputable source) where a connection string exists in web.config but I don't see explicit instructions to create the database and there's no included '.mdf'. The first time I build I got a runtime error regarding lack of permissions to CREATE database. So I created a blank db and made sure the string referenced a SQL user that had .dbo/owner rights to the db just created.
But subsequent builds don't seem to execute that same initialize db script - where ever that's stored.
Where is this 'first use' convention for creating databases documented?
thx
That is a feature of Entity Framework Code First. I am not sure what you are looking for exactly, but searching for "EF Code First Initialization Strategy" might help.
For instance read this article: EF Code First DB Initialization Using Web.Config
I assume you are talking about Entity Framework, which allows you to create the database from an instance of an ObjectContext object, which is used in any of the three approaches in EF (database-, model- and code-first).
Look for a line that actually calls ObjectContext.CreateDatabase(). If one of the supported ADO.NET provides is used (SQL Server or SQL Server CE 4.0) this will generate the required SQL Statements. Assuming the classic Northwind example, you might find something like that:
NorthwindContext context = new NorthwindContext();
if (!context.DatabaseExists())
{
context.CreateDatabase();
}
If this is in fact a code-first application, "lalibi" is right about the initialization strategy which by default doesn't require you to explicitly create the database. (But my guess is, that it actually uses a statement internally very similar to mine).

Resources