The code first creates the tables

I followed this tutorial and I tried to add some new columns to the userprofile table. And I tried to create a new table.

public class UsersContext : DbContext { public UsersContext() : base("DefaultConnection") { } public DbSet<UserProfile> UserProfiles { get; set; } public DbSet<TestTabel> TestTabel { get; set; } } [Table("UserProfile")] public class UserProfile { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } public string UserName { get; set; } public string Mobile { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } [Table("TestTabel")] public class TestTabel { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int TestId { get; set; } public string TestName { get; set; } public string TestMobile { get; set; } } 

Than I tried to update the database using the console with the update-database command, and I got this msg error:

The database already has an object named "UserProfile".

New columns that are not added, and no table.

What am I missing?

[EDIT] I ran the add-migration and update database commands, and that’s all (I had to run the update-database command twice, the second time with a detailed one).

 PM> Add-Migration cmdlet Add-Migration at command pipeline position 1 Supply values for the following parameters: Name: test Scaffolding migration 'test'. The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration 201304011714212_test' again. PM> Update-Database The project 'MVC4SimpleMembershipCodeFirstSeedingEF5' failed to build. PM> Update-Database Specify the '-Verbose' flag to view the SQL statements being applied to the target database. Applying code-based migrations: [201304011714212_test]. Applying code-based migration: 201304011714212_test. Running Seed method. PM> Update-Database -verbose Using StartUp project 'MVC4SimpleMembershipCodeFirstSeedingEF5'. Using NuGet project 'MVC4SimpleMembershipCodeFirstSeedingEF5'. Specify the '-Verbose' flag to view the SQL statements being applied to the target database. Target database is: 'aspnet-MVC4SimpleMembershipCodeFirstSeedingEF5' (DataSource: ., Provider: System.Data.SqlClient, Origin: Configuration). No pending code-based migrations. Running Seed method. PM> 

[/ EDIT]

Configuration.cs:

  namespace MVC4SimpleMembershipCodeFirstSeedingEF5.Migrations { internal sealed class Configuration : DbMigrationsConfiguration<UsersContext> { public Configuration() { AutomaticMigrationsEnabled = true; } protected override void Seed(UsersContext context) { WebSecurity.InitializeDatabaseConnection( "DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); if (!Roles.RoleExists("Administrator")) Roles.CreateRole("Administrator"); if (!WebSecurity.UserExists("test")) WebSecurity.CreateUserAndAccount( "test", "password", new { Mobile = "+19725000374", FirstName = "test", LastName = "test" }); if (!Roles.GetRolesForUser("test").Contains("Administrator")) Roles.AddUsersToRoles(new[] { "test" }, new[] { "Administrator" }); } } } 

In the "Filters" folder 1 cs file:

 namespace MVC4SimpleMembershipCodeFirstSeedingEF5.Filters { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute { private static SimpleMembershipInitializer _initializer; private static object _initializerLock = new object(); private static bool _isInitialized; public override void OnActionExecuting(ActionExecutingContext filterContext) { // Ensure ASP.NET Simple Membership is initialized only once per app start LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); } 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); } } } } } 

Connection string:

 <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> 

Last migration:

 namespace MVC4SimpleMembershipCodeFirstSeedingEF5.Migrations { using System; using System.Data.Entity.Migrations; public partial class test : DbMigration { public override void Up() { CreateTable( "dbo.TestTabel", c => new { TestId = c.Int(nullable: false, identity: true), TestName = c.String(), TestMobile = c.String(), }) .PrimaryKey(t => t.TestId); } public override void Down() { DropTable("dbo.TestTabel"); } } } 
+3
c # entity-framework-5 asp.net-mvc-4 code-first-migrations
Apr 01 '13 at 16:22
source share
1 answer

I'm just going to drop everything here as a walkthrough so that your code first and the migration goes - attack various problems that may or may not happen. Note: the first code turned out to be very reliable - and it can also be developed using live scripts - you just need to know what you are doing.

Most likely your migration and database are mostly out of sync.

Your existing migration is trying to work against an old copy of the database - with ups / downs that have been optimized for "empty db", I think.

You need to perform your Add-Migration against the copy of Db that you are attached to - this will create a “difference” and just update your Db (always make sure, back up , of course, as it may fall / change, etc. .).

Or, if possible, empty your Db and then run a new one.

Or if live Db - create migrations - and run Update-Database -Script on your dev machine - to generate full Db - or changes (all this is very rude, you need to adapt to your case). And then apply to your "live Db" by running scripts.

You can also check my previous post in sync ...

MVC3 and the first code migration - the model supporting the "blah" context has changed since the database was created

EDIT:
Also check this answer AutomaticMigrationsEnabled false or true?

And if everything is ok with your affairs, add AutomaticMigrationsEnabled = true; to you Configuration (also in the Migrations folder - created for you).

A couple of steps that I always take to clear migration:

(good for backup)
- Enable-Migrations -force (only for the first time - this removes the .cs configuration and any "seed" there!)
- AutomaticMigrationsEnabled = true;
- remove existing migrations manually from the project (\ Migrations)
- rebuild the project at this moment
- Initial migration with addition - Database update -Force -Verbose

... later (subsequent migrations):
- Add-Migration SomeOther1
- Database Update -Force -Verbose
... provided that you keep your Db in sync, that is, be careful with "moving the Db around," manually tuning, etc. (and in this case, see another post).

A couple of other things:

With PM Console ...
- select your project from the list,
- make sure that your "main exe" (calling your project / data assembly - or the same project, if the console / application) - is set as the "start" project,
- always see the console comments, as this may be an attempt to create and access another project.

Compound:

See this post of my migration does not change my table
In short, your connection is called your context + your project - unless otherwise indicated. It is extracted from your DbConfig constructor or app.config (connections). Make sure that you look at the “correct database” (that is, what you are viewing through some kind of explorer and which code you are connecting to first) there can be two different things).

Construction:
Make sure your project is installed in the “configuration” for automatic assembly - this can also be a problem.

+14
Apr 01 '13 at 16:47
source share



All Articles