Execute Code First Migrations is Grayed Out in Publish Settings - asp.net-mvc-3

Using Windows Azure and attempting to publish my MVC3 Application. The check box for Execute Code First Migration in the settings panel of the Publish web application is grayed out. What changes do I need to make to be able to enable it?

I believe you see the following "Execute Code First Migration" disabled when you try to publish your MVC application:
This is potentially because either you do not full code written for Code migration in your application as well no or incorrect DB setup in your web.config as described here.
In order to have Code Migration enabled, you must have a DB configured (in case of Windows Azure you need to provide SQL Database info in the web.config) in web.config and a complete class is written on how the code migration will happen depend on your model. Here is an example on how to achieve it.
http://msdn.microsoft.com/en-us/library/dd394698#efcfmigrations

I am assuming that you have Entity Framework model and in your database already (if not then you need to do some reading, answer by #AvkashChauhan would be indeed a good starting point).
However if you do have a model and all the configurations like:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new YourEntityMap());
}
and all the entity mappings like:
public class YourEntityMap : EntityTypeConfiguration<YourEntity>
{
public YourEntityMap()
{
this.HasKey(t => t.Id);
}
}
and you still don't get the darn checkbox enabled you might want to do following steps:
Go to Tools > NuGet Package Manager > Package Manager Console
Then in console write
Enable-Migrations -ContextTypeName Company.Models.YourDevContext
where Company.Models.YourDevContext is your Database Context (look for class that inherits from DbContext should be same one that has OnModelCreating override).
after running command you should get something like:
At this point you should have Migrations folder added to the solution more on how to handle migrations here
Hope this saves you some time.

Related

model changed, update database using codefirst

Im using code-first to create a database. And now im trying to make a linq expression to get data out of the database but then i get this error:
"The model backing the 'FantasySport' context has changed since the database was created. Consider using Code First Migrations to update the database"
So i go to package-manager console and types update-database and it says that there is nothing to update.
"PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No pending code-based migrations.
Running Seed method."
----EDIT------
Here is the initializer method:
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
So what is the problem?
You first have to add a migration to update to. You can do it by typing the following command in the package manager console:
add-migration "a custom name for your migration here..."
This will cause a migration to be created, after which you can run the Update-database command from the package manager console.
[EDIT]
The Database.SetInitializer method specifies the strategy for creating and seeding your database on the fly. Since that is what is causing this error, and since we are manually creating and seeding your database through the update-database command, we want to turn it off. http://www.codeguru.com/csharp/article.php/c19999/Understanding-Database-Initializers-in-Entity-Framework-Code-First.htm
To be able to update the database through migrations you have to use the
add-migration "<migration-name>"
command however I've experienced it getting "stuck" sometimes meaning that you will get this error or it will display the usual message that there is a need for another migration step. To solve this make sure that
there is no hidden migration file which was not deleted just removed from the project
always build the project after an add-migration command before issuing the update-database command
make sure the connection string to the database is the same in the project you issue the update-database command points to the same database your program uses.
Other than this you can check whether the __MigrationHistory table contains all the migration steps including the newest as the Entity Framework tests the current model against this table's records.
Some of these voodoo (like rebuilding and cleaning) was only required around EF 4.4 I guess the update-database script was improved in this area as well.

How can I replace config file database links in one place in source code? (asp.net/razor)

I have an ASP.NET/Razor 3 web application which uses a SQL Server database via MS EntityFramework.
If/when I want to change the database connection string, for example to change the password or point to a different database (e.g. test vs. live), the string needs to replaced in about seven places in three different XML config files in the project (app.config, web.config, and app.release.config), which is an error-prone pain.
Worse, the default web server behavior on unhandled exceptions can include displaying sections of the config files to web users, which has in fact resulted in the web server displaying the lines that show the database path and password over the web. Not good.
For both reasons, and because this is not a product for which anyone would ever just edit the config file on the server (any change is pretty much, and may as well be, a build operation), I would much prefer to have the database connection information compiled into the web application and loaded from code rather than a config file, and to be able to do this such that when I want to change the database information, I can do it in one place instead of seven.
How would I achieve this?
The database connection string(s) can be set up centrally in 1 place, in the Global.asax.cs file, as part of the Application State, and then referenced from anywhere else in the project.
Step-1: Define the connection string(s) as static variables in Global.asax.cs:
namespace TestProject
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static string ConnectionString1;
public static string ConnectionString2;
protected void Application_Start()
{
#region Build application state for the app-specific items needed by us
ConnectionString1 = "Server=yourserver;Database=yourdb;etc etc";
ConnectionString2 = "Server=yourserver;Database=yourdb;etc etc";
#endregion
#region Code auto-generated and needed by system - do not change
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
#endregion
}
}
}
Step-2: Use the strings from anywhere else in the project:
string cnxStr1 = TestProject.MvcApplication.ConnectionString1;
string cnxStr2 = TestProject.MvcApplication.ConnectionString2;
(Please note that by default, the strings would be accessible only from within the same project. You will need to add references to the project if you need to use the strings from any other project within the same solution.)
The answer above by Krishna is pretty good. For me I would personally prefer to have them as static string in a static class and use it where ever is needed.
If you don't want to put the connection strings in the global file, you can:
Create a separate .config file for connection strings. e.g.
connectionStrings.config.
Create a hard-link to this file or the
folder containing this file that's in the same directory as your
other application.config and web.config files.
Set the configSource property on the connectionStrings element in each app.config or
web.config.
From then on, you only have one place to manage your connection strings that are common between apps.
The reason for the hard link is that configSource must reference a file in the same folder or sub-folder of the folder containing the application config.
Note that changing the connection strings will recycle all your web application pools that use them. For console, desktop, and service apps, you will have to restart for changes to take effect.
For the second problem you describe, you could have a separate connectionStrings.config file for each environment: development, test, production. Using config transforms or some other process, you only have to update the configSource property in each connectionString element to switch environments.

How to hide connectionStrings on Github for both Entity Framework and Membership, that will be used on AppHarbor later on?

I know the title looks somewhat confusing so let me explain. :)
I have a MVC 3.0 Project for which I maintain a public repository # github, and said Project utilizes the Entity Framework and the Membership Provider (so that's two separate connectionStrings) .
The issue I am having is that the "Alias" attribute of Sequilizer for the MS SQL database, let's me specify only one connectionString value to be replaced at build time. Because I can not modify web.config programmatically (and web.config transformations are not applicable because it will leave my sensitive data open to the World on the public github repo), I am left to choose which I want to use more -> Entity or Membership (the other solution would be leaving one of my connectionStrings vulnerable) .
Due to the need of MembershipProvider to know the connectionStringName at build time (everything is specified in web.config), I am kinda at a loss of how to go about all this.
Any help is appreciated!
Cheers
Okay guys, I think I set up everything finally.
What I did is, I used the Alias only for my normal connection string which will provide Membership stuff - while I overrode the ObjectContext default constructor (in "MyProjectEntities.Designer.cs") to use Configuration Variable (named "EntityFramework") that I set up on AppHarbor which holds the Entity Framework connectionString like so:
public MyProjectEntities() : base(ConfigurationManager.AppSettings["EntityFramework"].ToString(), "eTestHubEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
Tested and works as I wanted it to work. :)

MVC3 code first: migrations and generating the database

I'm a bit lost how I should get the entity framework to work with automatic migration. I want:
The database to be created automatically when it doesnt exist
The database to be updated automatically when the model changed
For the latter I'm using DbMigrator. It is rather slow so I don't want to run it every request, and also I have multiple databases in the same application so it cant go in Application_Start which is why I put it in Session_Start like this:
if (Session["started"] == null)
{
// this takes care of any database updates that might be necessary.
MigrationConfiguration configuration = new MigrationConfiguration();
DbMigrator migrator = new DbMigrator(configuration);
List<string> pm = migrator.GetPendingMigrations().ToList();
if (pm.Count > 0)
{
migrator.Update();
}
}
else
{
Session["started"] = "started";
}
Not sure if this is the right way to do it but it seems to work, however it doesnt actually generate the database when it doesnt exist. It gives me a "Cannot open database "db" requested by the login"
I had this working before with the following:
Database.SetInitializer<DbContext>(new InitializerIfModelChange());
This drops the database and generates seed data which is fine for when the database doesnt exist but it also is triggers when the database is changed (in which case I would like DbMigrator to handle it) This was in Application_Start before but I'm not sure what to do with it. I'm afraid that it will conflict with the DbMigrator. How would I set this all up in order to achieve the two things described earlier?
I manually run the Update-Database in the package manager whenever the database needs to be changed. Initially I used the Database.SetInitializer like you did to create the database but have it commented out now.
Checkout Entity Framework 4.3 Automatic Migrations Walkthrough for more advanced help.
This should work for what you want, then if you need to create a new database just add Database.SetInitializer<NewDBContext>(new NewDBInitializer()); like you had, build and run. Then comment it out so it doesn't run in the future on a model change and instead use the Update-Database command in the package manager.

Model First scaffolding not working in ASP.NET MVC3 Application

I am building a controller using scaffolding, from a database model.
The database in the backend is SQL Azure, although I am not sure if that matters.
I entered the connection string, and tested, and it works. I added a new ADO.Net Entity Data Model to my models, and it created the mappings, and I can view the table structure and the FKs when I open the created model, and it looks correct.
I built the solution so the new model is available.
I made sure I have the latest version of Entity Framework, and downloaded the MvcScaffolding from NuGet.
When I add new controller with read/write actions and views, using Entity Framework, I get the following error:
The type 'Website.Models.App.Application' was not mapped.
Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation.
Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.
When I try to add the same controller using MvcScaffolding: Controller with read/write actions and views, using EF data access code, I do not get an error at this step, but when I navigate to the Index View of the new controller I get the same error.
Any ideas about what is causing this error? I have seached long for a solution but everything is coming up empty. Thank you.
Install Net DbContext Generator, if not available from online templates in your Visual Studio 2010
in the entity designer (.edmx file), right click on a blank area, click 'Add Code Generation Item', select 'ADO.NET DbContext Generator' give it a name, click add. >>cant remember why you have to do this :-( but it fixed the same problem for me.
You probably nested your your classes in the main class:
static void Class main(string[] args)
{
public Class YourClass() // This is the wrong location, it's nested in the main class
{
...
}
}
public Class YourClass() // This is the correct location
{
...
}

Resources