If you have automatic migrations set up this should be pretty straight forward.
If you haven't, you will need to run Enable-Migrations –EnableAutomaticMigrations
Perhaps do some further reading here first though: http://msdn.microsoft.com/en-gb/data/jj554735.aspx
For anyone looking to update a database with a new table (say I want to add an UserAttachment table to sit alongside my existing User table) using EF code first, do the following:
With automatic migrations enabled you should ensure you have...
1.) Create your new model as you see fit.
2.) Create your Configuration file, something along the lines of:
class UserAttachmentConfiguration : EntityTypeConfiguration<UserAttachment>
{
public UserAttachmentConfiguration()
: base()
{
HasKey(p => p.UserId);
ToTable("UserAttachment");
HasRequired(t => t.User)
.WithOptional(t => t.UserAttachment);
}
}
3.) Add your DbSet
and modelBuilder
data in your main Context.cs
file
DbSet
public DbSet<UserAttachment> UserAttachment {get; set;}
modelBuilder
modelBuilder.Configurations.Add(new UserAttachmentConfiguration());
4.) Run update-database
via Visual Studio's Package Manager Console
, make sure you have selected the correct project from the drop down, this is likely to be a .Repository
named project.
Your new table should now exist in your database.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…