2

Teaching myself .Net Core web stuff.

I have a model and I have successfully created my DB.

Now, I am adding a new Field to my model/class. I want to preserve existing data in this table so do not want to recreate the DB/Table. How can I update the DB/Table>

I have tried using 'Update-Database' in the Package Manage Console but got an error telling my table already exists. Which I know it does. But I am updating not creating.

This is my model:

public class Subscription
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long SubscriptionId { get; set; }
    public string SubscriptionRef { get; set; }
    public string CompanyName { get; set; }
    public string EmailAddress { get; set; }
    public string Salt { get; set; }
    public string Key { get; set; }
    public bool Disabled { get; set; }
    public DateTime DOE { get; set; }
}

This is my DBInitalizer

public class DbInitializer
{
    public static void Initialize(WorkerContext context)
    {
        context.Database.EnsureCreated();
        context.SaveChanges();
    }
}

Which is called by my startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<WorkerContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddMvc();
}

This is my DB context:

public class WorkerContext : DbContext
{
    public WorkerContext(DbContextOptions<WorkerContext> options) : base(options)
    {
    }
    public DbSet<Models.Subscription> Subscriptions { get; set; }
}

So now I add a new field to my Subscription Table/Model:

public string Test { get; set; }

I rerun the project (i also type in Update-Database) and no new field is created...

How do I update/edit/modify/delete tables and fields using code 1st techniques?

Thanks

4
  • 1
    You need to further explore how EF Core Migrations works. Commented May 19, 2017 at 16:42
  • Hi, thanks for that link. Good of you Commented May 19, 2017 at 16:43
  • @FedericoDipuma I would have deleted this question as it now seems obvious but some one has kindly supplied the answer so wrong to do so. Commented May 19, 2017 at 16:44
  • please write you errors here Commented May 19, 2017 at 16:46

1 Answer 1

1

you have to use:

dotnet ef migrations add "MigrationName" -c ContextName
dotnet ef database update -c ContextName

and to remove migration:

dotnet ef migrations remove

this will remove latest migration

Sign up to request clarification or add additional context in comments.

1 Comment

The first line should be dotnet ef migrations add "MigrationName" -c "ContextName"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.