EntityFrameWork Migration Asp.net Core 2.0

335 Views Asked by At

I have a Asp.Net core 2.0 project, with Entity framework Core 2.0Version. I have an existing database. Now enter packagemanager console window: Add-Migration then Name:InitialMigration after Migration folder added in my project. Then I Type Update-Database comment in package manager console window. 'Table already exists' error message display. Because already that table have in my db.

My requirement is when add or remove property in my existing model that property automatically update in my existing database. how can i do it?

2

There are 2 best solutions below

4
bugrakosen On

You must remove database and update database after re-create migration. But if you want update in your database tables, you can create another migration and update database without remove existing "InitialMigration".

After adding property in your Entity create new migration and output will be like below;

public partial class UpdateDatabase : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AddColumn<string>(
            name: "Description",
            table: "Category",
            type: "longtext CHARACTER SET utf8mb4",
            nullable: true);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropColumn(
            name: "Description",
            table: "Category");
    }
}

And you can update database with update with Update-Database command or;

  yourDbContextObject.Database.Migrate();

You should see added new column with null values to all rows in database.

Or, you can add custom attribute on your property like below;

/// <summary>
/// Attribute for adding default value in context level.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class MilvaDefaultValueAttribute : Attribute
{
    /// <summary>
    /// Specifies this property has a default value upon creation.
    /// </summary>
    /// <param name="defaultValue">The default value of the property.</param>
    public MilvaDefaultValueAttribute(object defaultValue)
    {
        DefaultValue = defaultValue;
    }

    /// <summary>
    /// Default value of tagged property.
    /// </summary>
    public object DefaultValue { get; private set; }
}


public class Category : BaseEntity
{
    [MilvaEncrypted]
    public string Name { get; set; }

    [MilvaDefaultValue("Default value added.")]
    public string Description { get; set; }

    public List<Todo> Todos { get; set; }
}

And override OnModelCreating method in your DbContext and use this extension below;

    public static void ConfigureDefaultValue(this ModelBuilder modelBuilder)
    {
        foreach (var entityType in modelBuilder.Model.GetEntityTypes())
            foreach (var property in entityType.GetProperties())
            {
                var memberInfo = property.PropertyInfo ?? (MemberInfo)property.FieldInfo;

                if (memberInfo == null) continue;

                var defaultValue = Attribute.GetCustomAttribute(memberInfo, typeof(MilvaDefaultValueAttribute)) as MilvaDefaultValueAttribute;

                if (defaultValue == null) continue;

                modelBuilder.Entity(entityType.ClrType).Property(property.Name).HasDefaultValue(defaultValue.DefaultValue);
            }
    }

This attribute and extension method in my library. I couldn't add documentation because I didn't have time, but there is documentation within the code and sample app exists in github project.

I hope I could help.

0
Salahuddin Ahmed On

Following steps might work for you!

Remove-Migration InitialMigration
Add-Migration name_of_new_migration
Update-Database -Force

If the above steps not working then try the following steps:

Add-Migration Initial -IgnoreChanges

This will create a blank migration script

Update-Database

This will update the database to this migration but no changes will be applied. You can now add your changes to the database context. After you have finished do the following step.

Add-Migration name_of_new_migration

This will generate a new migration script with your changes in it. Then update your database again.

Update-Database