Reputation: 7344
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
Upvotes: 2
Views: 4537
Reputation: 411
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
Upvotes: 1