Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code first create tables

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");
    }
  }
}
like image 794
Yustme Avatar asked Dec 03 '22 23:12

Yustme


1 Answers

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.

like image 101
NSGaga-mostly-inactive Avatar answered Dec 28 '22 21:12

NSGaga-mostly-inactive