How to Enable Migration to update my database in MVC4? - c#

I'm working on a project using MVC4 in Visual Studio 2012 and have added a column in the table.
Now when I want to debug my project the error says to use the migration to update my database.
What I have to do?
I have been searching a lot and found some methods like:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<ResTabelaIndex>(null);
}
but don't know how and where to implement this... Have tried in app_start, global.asax etc...
What I found was, to enable the migrations directly in the console from the nuget.
But I can't make this work.
Commands I use:
Enable-Migrations -EnableAutomaticMigrations
==> Console says that more than one context was found .
To enable use, Enable-Migrations -ContextTypeName NameOfTheNamespace.Models.DefaultConnection
But I don't know what is the -ContextTypeName, have tried a lot but couldn't understand.
My Model Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.Migrations;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Infrastructure;
namespace Vista.Models
{
public class TabelaIndex
{
public int ID { get; set; }
public string n_empresa { get; set; }
public string titulo{ get; set; }
public string url { get; set; }
public string imagens { get; set; }
}
public class DefaultConnection : DbContext
{
public DbSet<TabelaIndex> ResTabelaIndex { get; set; }
}
}

Commands:
enable-migrations default context
add-migration InitialCreate (for generating snapshot)
add-migration InitialCreate (to apply snapshot)
update-database
update-database -verbose
Detailed explination will here:
http://www.dotnet-tricks.com/Tutorial/entityframework/R54K181213-Understanding-Entity-Framework-Code-First-Migrations.html

The error is saying that you have two contexts. When you first create a project using MVC 4, Visual Studio creates a context for your SimpleMembership by default (check Models/Account.cs) or do a ctrl+f for UsersContext, you can just delete this file if you are not using SimpleMembership.
After removing this context, go ahead and add the following to your DefaultConnection class:
protected override void OnModelCreating(DbModelBuilder builder)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultConnection,Configuration>());
}
If you enabled migrations correctly you should also have a folder called Migrations and inside it a Configuration class, its constructor should look like this (if you want to enable automatic migrations):
public Configuration()
{
AutomaticMigrationsEnabled = true;
}

Try typing this into the console:
Enable-Migrations -ContextTypeName Vista.Models.DefaultConnection
Vista.Models.DefaultConnection is your context (the class that inherits from DbContext).

If you have small changes not need migration. You can add column to any table on database with sql script and add property to model and delete metadata table. (back up database firstly no doubt).
Or you can use Migrations like this: aspnet-mvc-4-entity-framework-scaffolding-and-migrations

Related

How can I create many tables in my database using EF Core migrations

I am doing a bookstore project and I first created one table for the adding book.
So I want to add login and signup pages and store to the database, but I am confused about how I can add another table or create tables related to my need using migrations. I have attached my DbContext class.
Forgive me my English is not so good. I am waiting for your answers. Thanks
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CODEwithZAKI.Data
{
public class BookStoreContext : DbContext
{
public BookStoreContext(DbContextOptions<BookStoreContext> options)
: base(options)
{
}
public DbSet<Books> Books { get; set; }
}
}
Dbcontext Class
For how to add a new table to the database with ef core code first, you can follow the below steps:
1.Create your new table as a model
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
//other properties
}
2.Add its entry in DbContext class
public class BookStoreContext : DbContext
{
public BookStoreContext(DbContextOptions<BookStoreContext> options)
: base(options)
{
}
public DbSet<Books> Books { get; set; }
public DbSet<Author> Authors { get; set; }
}
3.Create a new migration with the addition of Posts in Package Manager Console
Add-Migration AuthorMigration
4.Update database
Update-Database
To add new tables to you database using migrations is simply a matter of extending your BookStoreContext with the new sets and then running the migration commands. As an example using dotnet command.
Generate the new migration script:
dotnet ef migrations add DESCRIPTION_OF_YOUR_MIGRATION
Run the migration:
dotnet ef database update
And that's it. Everytime you add new records to your BookStoreContext you just go through the above two commands to run the EF Core migration process.
PS For login/authentication/identity it is recommended to utilize ASP.NET Core Identity.

Consuming View in EF Code First conflicts with migration

I have a Table "IncomingChecks" in my database. I've created it using EF Code first. Now, I've added a view to my database based on this table named "ViewIncomingChecks" using Sql Server Management Studio and I want to use its data in my app using Entity Framework.
I copied the model class and changed its name and added it to the context:
public class ViewIncomingCheck
{
[Key]
public int Id { get; set; }
//...
}
public class CheckDataContext : DbContext
{
public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks { get; set; }
//...
}
now when I run the app, it throws an exception saying the DB Context has been changed and needs a migration. I even tried to add a migration (which seems to be the wrong option) and when I add the migration, it says that the object ViewIncomingChecks is already in the database.
How can I use this view in my code?
Edit
My current solution is to have another context just for the views. This way it doesn't conflict with the EF Migrations. Is this the best option or is there a better way to deal with it.
According to what I have done in my project:
First add public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks
{ get; set; } to your DbConext
Now create a migration something called ViewDbSetAdded
Remove all the code from the both Up and Down method and it will look like as follows:
Migration Code:
public partial class ViewDbSetAdded : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
Now run update-database command and it will run an empty migration.

Ef migration error when using default connection string on constractor

In my solution I have some database contract project that stores interfaces for contexts and some project for concrete Ef contexts, something like below:
public interface ISampleContext
{
IDbSet<User> Users { get; set; }
IDbSet<Session> Sessions{ get; set; }
}
public class SampleContext : DbContext, ISampleContext
{
IDbSet<User> Users { get; set; }
IDbSet<Session> Sessions { get; set; }
SampleContext() : base("name=EfDefaultConnectionString"){ ... }
SampleContext(string connectionString) : base(connectionString){ ... }
protected override void OnModelCreating(DbModelBuilder modelBuilder) { ... }
}
I run the command for migration (enable, add, update, etc.) by below pattern:
Add-Migration
-Name MigrationName
-ProjectName EfProjectName
-StartUpProjectName EfProjectName
-ConfigurationTypeName EfProjectName
-ConnectionStringName SomeConnectionStringName
But after running the commands, Ef migration fails. For solve problem, I should comment interface(s) and : base("name=EfDefaultConnectionString"). finally, after create migration uncomment code.
My question is why when provide connection string name, package manager console not call the SampleContext(string connectionString) constructor and I get below exception?
No connection string named 'EfDefaultConnectionString' could be found in the application config file.
And second question is can I control the flow of running commands in package manager console?
last question is not exactly related to this problem, but I need now Is there any way run migration commands when "EntityFramework.dll" and "EntityFramework.SqlServer.dll" "copy local" is false?

How do I get Entity Framework Code First Migrations to see my models?

I made a new ASP.Net Web Application and enabled migrations on it. I ran add-migration initial and the initial migration does in fact have all the default tables for authentication (dbo.AspNetRoles, dbo.AspNetUserRoles, etc). However, when I create my own context and add an entity model to it, I can't get migrations to acknowledge that model. That is, when I run add-migration added-watchedgame-model I just get an "empty" migration file. So what am I doing wrong? Does my DbContext have to be referenced somehow? can Entity Framework only handle migrations for 1 dbcontext?
ReleaseDateMailerDBContext.cs:
using System.Data.Entity;
using WebApplication4.Models;
namespace WebApplication4.DataAccess
{
public class ReleaseDateMailerDBContext : DbContext
{
public ReleaseDateMailerDBContext() : base("DefaultConnection") { }
public DbSet<WatchedGameModel> WatchedGameModelSet { get; set; }
}
}
WatchedGameModel.cs:
using System.ComponentModel.DataAnnotations;
namespace WebApplication4.Models
{
public class WatchedGameModel
{
public int ID { get; set; }
[MaxLength(1024)]
public string URL { get; set; }
public string Email { get; set; }
public bool EmailSent { get; set; }
}
}
"empty" migration file:
namespace ReleaseDateMailer.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class addedwatchedgamemodel : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
"Batch Clean" may resolve your porblem.
It suggests that the EF tooling/assemblies are looking in a location other than the default build output location (typically /bin/Debug). The clean command also, incidentally, clears intermediary outputs.
To do a batch clean:
Select Build -> Batch Build
Click Select All
Click Clean
Close dialog, rebuild and re-attempt migration.
While running the add-migration command your package manager console should be pointed to the project having your DBContext class (WebApplication4.DataAccess).
If you have migration in a different project than your web application project (suppose WebApplication4.Web) then you should run the following command:
add-migration "MigrationName" -projectName:WebApplication.DataAccess -startupProjectName:WebApplication4.Web
Hope it helps!!
With the built-in asp.net mvc project, a DbContext class (ApplicationDbContext) is already
created!
When you enter enable-migrations, a migration configuration class is created based on the dbcontext class that it finds.
When you enter add-migration "migrationname", That dbcontext class is what is checked for differences.
So all one has to do is, rather than making one's own class that derives from DbContext, use that one.

Infrastucture does not exist in System.Data.Entity

I am trying to create MVC project with Entity Framework.
I have 3 Projects in Solution
SerialTracker.Common
SerialTracker.Model
SerialTracker.Web
Common and Model are compiled like library, so Web is using them.
Model is also using Common.
My probelm is here:
Model generate from *.edmx ==> *.Context.tt ==> whitch auto generates *.Context.cs:
namespace SerialTracker.Model
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class SerialTrackerEntities : DbContext
{
public SerialTrackerEntities()
: base("name=SerialTrackerEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Role> Role { get; set; }
public DbSet<User> User { get; set; }
}
}
I have error, that Infrastucture does not exist in System.Data.Entity. I tried adding some References, but i think the problem is in another place.
//EDIT:
I reinstaled NuGet package for this project, but now i have error and doesn't exist
Sorry for my poor English.
S̶o̶ ̶I̶ ̶m̶a̶n̶u̶a̶l̶y̶ ̶a̶d̶d̶e̶d̶ ̶f̶i̶l̶e̶ ̶S̶e̶r̶i̶a̶l̶T̶r̶a̶c̶k̶e̶r̶.̶t̶t̶ ̶t̶o̶ ̶S̶e̶r̶i̶a̶l̶T̶r̶a̶c̶k̶e̶r̶.̶e̶d̶m̶x̶.̶
T̶h̶i̶s̶ ̶f̶i̶l̶e̶ ̶I̶ ̶c̶o̶p̶i̶e̶d̶ ̶f̶r̶o̶m̶ ̶a̶n̶o̶t̶h̶e̶r̶ ̶p̶r̶o̶j̶e̶c̶t̶.̶
N̶o̶w̶ ̶i̶s̶ ̶p̶r̶o̶j̶e̶c̶t̶ ̶g̶e̶n̶e̶r̶a̶t̶e̶ ̶e̶n̶t̶i̶t̶i̶e̶s̶ ̶R̶i̶g̶h̶t̶.̶
EDIT (04-29-2014):
Renewed answer:
You can delete file *.tt and recreate it with
Add -> New Item -> EF 5.x DbContextGenerator (or EF 6.x ...)

Categories