4

I was following this tutorial, and I tried to add a few new columns in 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 with the console with the update-database command, and i got this error msg:

There is already an object named 'UserProfile' in the database.

The new columns where not added, and neither the table.

What am I missing?

[EDIT] I did the add-migration and update-database commands, and this is the out come (had to do the update-database command twice, 2nd time with verbose)

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");
    }
  }
}
Yustme
  • 6,125
  • 22
  • 75
  • 104
  • 2
    Hi there, did you run the `Add-Migrations` [command](http://msdn.microsoft.com/en-us/data/jj591621.aspx) to scaffold your changes before running `Update-Database`? – nkvu Apr 01 '13 at 16:37
  • Hi, yea i tried that too btw, forgot to mention that. But it didn't work. – Yustme Apr 01 '13 at 17:00

1 Answers1

17

I'm just going to throw everything in here as a walk-through for getting your code-first and migrations going - attacking various issues that may or may not happen. Note: code-first has proved to be very reliable - and can be worked out with live-scenarios as well - you just need to know what you're doing.

Most likely, your migration and the database are basically out-of-sync.

Your existing migration tries to run against the old copy of the database - with ups/downs that were optimized for the 'empty db' I guess.

You need to run your migrations (Add-Migration) against the copy of the Db that you're attaching to - that'll create a 'difference' and just up-to-date your Db (always make sure to backup of course, as it might drop/change etc.).

Or if possible, empty your Db - and then start fresh.

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

You can also check my earlier post on the synchronization...

MVC3 and Code First Migrations - "model backing the 'blah' context has changed since the database was created"

EDIT:
Also check this answer AutomaticMigrationsEnabled false or true?

And if it's ok with your way of doing things add the AutomaticMigrationsEnabled = true; to you Configuration (also under the Migrations folder - created for you)..

Couple steps I always do to clean migrations:

(good to backup first)
- Enable-Migrations -force (first-time only - this deletes the configuration.cs and any 'seed'-ing there!)
- AutomaticMigrationsEnabled = true;
- remove existing migrations by hand from project (\Migrations)
- rebuild the project at this point
- Add-Migration Initial
- Update-Database -Force -Verbose

...later on (subsequent migrations):
- Add-Migration SomeOther1
- Update-Database -Force -Verbose
...providing you keep your Db in sync - i.e. careful with 'moving Db around', manually adjusting etc. (and in that case see the other post)

Couple other things:

With PM Console...
- select your project from the list,
- make sure your 'main exe' (calling your data project / assembly - or that same project if console/app) - is set as 'startup' project,
- always watch the console comments - as it may be trying to build and access different project.

Connection:

See this post of mine Migration does not alter my table
In short - your connection is named like your context + your project - if not specified otherwise. It draws from your DbConfig constructor - or app.config (connections). Make sure you're looking at the 'right database' (i.e. what you look through some explorer and what code-first connects to - may be two different things).

Building:
Make sure your project is set in 'configuration' to build automatically - that can be an issue too.

Community
  • 1
  • 1
NSGaga-mostly-inactive
  • 14,052
  • 3
  • 41
  • 51
  • So code first is not doing this for me when i run the add-migrations and then the update-database command from the console automatically? I rather do it from code than puzzling with scripts. – Yustme Apr 01 '13 at 17:04
  • yes it is doing it for you - but you 'missed a step' somewhere along the line - as it's obviously out-of-sync for some reason. Script is only for 'live server' updates, not for testing/dev etc. Just start with 'Add-Migration' again - and see what happens - if you are on the local machine. Migrations do lot of things for you - but often fail when 'moving things' to different machine - the 'old Db' had to be made by migrations as well - so it can just 'continue' applying migrations. If it isn't this happens. – NSGaga-mostly-inactive Apr 01 '13 at 17:09
  • are you 'live' or 'local' ? If local, can you just try removing (back up first) the db and it should recreate it for you (since this is obviously a test for you that's easiest). So steps are - remove Db, remove 'all migration files' as well (all #####...cs files under Migrations folder) - rebuild the project - then 'Add-Migration' - then Update-Database -verbose - and check migration cs and script generated - you can post that - this is easy to resolve, unless remote – NSGaga-mostly-inactive Apr 01 '13 at 17:15
  • It's a test yes, but this is for a real project i'am going to work on, if i figure this out. And if i do go live with it, and change something in the data model. I don't want to delete everything and recreate it. I've edit my original post with the migration commands out come. – Yustme Apr 01 '13 at 17:19
  • should the methods up() and down() contain some code in the #######.cs file? Because they are empty. – Yustme Apr 01 '13 at 17:31
  • yes they should (if there is difference). Could you check your Db - the one mentioned in the PM console - is that the one you're using? does it have the tables you need. From your comments above - it seems like it goes well - just nothing to change – NSGaga-mostly-inactive Apr 01 '13 at 17:32
  • Yea i just looked into it. The database hasn't changed from the tutorial i followed. Even with the newly added columns. Not sure where exactly the code for a new table should be, but i placed it under the 'userprofile' table in the tutorial which is in the AccountModels. – Yustme Apr 01 '13 at 17:35
  • Check your connection - e.g. what you're 'looking at' from db explorer - and the one code-first is accessing. To start fresh - just remove that same db - or clean tables, go back and then try again - you should then see 'the difference' - just do all steps and be consistent (remove everything, then rebuild - then Add/Update. – NSGaga-mostly-inactive Apr 01 '13 at 17:35
  • ok then - could you post your DbContext version? You need to put your table as `DbSet<>` in there as well - or make some relationship in fluent/code - for it to be considered. Just 'making a table' doesn't do anything. – NSGaga-mostly-inactive Apr 01 '13 at 17:37
  • Original post has been updated. I can see now that the table has been created. I added the DBSet<> for the testtable. But the new columns for the user table hasn't been added. – Yustme Apr 01 '13 at 17:45
  • check [this post](http://stackoverflow.com/questions/14946107/connectionstring-defaultconnection-was-not-found) - check your app.config. Just try from the clean db as I suggested, make sure connection - and fields should be there, if it adds the table. Do 'cleanup' (as I said) and post migration cs etc. It's something simple we're missing, I have to run but will check later on. – NSGaga-mostly-inactive Apr 01 '13 at 18:15
  • I haven't touched the connectionstring from the tutorial. The last migration is posted aswel. But i updated my post again with the connectionstring. What exactly do you mean with clean up? Deleting the database? If i do that it will most definitely work. But i need to have an update example, without removing things. – Yustme Apr 01 '13 at 18:29
  • you need to cleanup first - you'll get to updates then. do this http://stackoverflow.com/questions/14946107/connectionstring-defaultconnection-was-not-found - replace w/ your connection/db if needed. Migration is looking fine, you have fields - fields should be added too. – NSGaga-mostly-inactive Apr 01 '13 at 18:55
  • What exactly do you want me to do from that post? I have a working connectionstring? And what kind of clean up are you talking about? – Yustme Apr 01 '13 at 20:08
  • dude, take a deep breath :) - and go through slowly - I can only do so much - and make a narrow/specific issue - maybe spawn another Question (@ me here and I'll take a look when I manage, I have so much work to do). Cheers! – NSGaga-mostly-inactive Apr 01 '13 at 20:38
  • 1
    I was just trying to clear things up. I'm very calm. Think i'll do that. – Yustme Apr 01 '13 at 21:25