Reputation: 4607
I have an MVC4 internet application using forms authentication.
Out of the box the UserProfile
model is created in the Account models file, I have moved that to its own file and called DbSet<UserProfile
> in my DbContext
file. I expected EF to create a 2 table database, UserProfiles and Stories.
public class MySocialStoriesDb : DbContext
{
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<Story> Stories { get; set; }
}
Story Model
[Table("Stories")]
public class Story
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int StoryId { get; set; }
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile User { get; set; }
public string File { get; set; }
public DateTime DateCreated { get; set; }
public string Name { get; set; }
}
UserProfile Model
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string EmailAddress { get; set; }
public string UserDirectory { get; set; }
public bool Paid { get; set; }
public DateTime DatePaid { get; set; }
public string PaymentId { get; set; }
}
I have run Enable-Migrations from Package Manager and allowed automatic migrations and allowed dataloss. The InitialCreate file generated only seems to create the User Profile table, it doesn't have anything in its code for the Story table.
I added the following line to Global.asax
Database.SetInitializer(new Models.IntializeMySocialStoriesDb());
If i now change a model nothing on the database changes. If i manually drop the database and change the InitializeMySocialStoriesDb
to DropCreateDatabaseAlways and then run the app, the database is not created.
I am just wondering what I have missed.
Upvotes: 1
Views: 577
Reputation: 8112
Don't bother with this mechanism. It's not feasible for production apps and requires you to hose all your data each time the schema changes.
Instead create your database schema as a separate SSDT project and use DACPAC files to initially deploy and upgrade your production database while keeping all the data intact. Just copy the tables that SimpleMembership creates into your SSDT project.
This way you have exact column definitions, can exactly define constraints, exactly define foreign keys, primary keys and unique keys etc. and still access your data through Entity Framework in your application project. Upgrading the schema on the production database simply requires a DACPAC to be deployed.
During development, Visual Studio will automatically make any changes to the table structure when you make changes in SSDT.
In short I think code-first is too loosely defined, unorganised and a bad idea.
Upvotes: 2