MVC4项目 - 不能DropCreateDatabaseIfModelChanges

时间:2013-04-23 10:56:52

标签: c# entity-framework asp.net-mvc-4

我有一个使用表单身份验证的MVC4 Internet应用程序。

开箱即用的UserProfile模型在帐户模型文件中创建,我已将其移至自己的文件并调用DbSet<UserProfile&gt;在我的DbContext文件中。我希望EF能够创建一个2表数据库,UserProfiles和Stories。

public class MySocialStoriesDb : DbContext
{
    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<Story> Stories { get; set; }
}

故事模型

[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模型

[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; }
}

我已从Package Manager运行Enable-Migrations并允许自动迁移和允许数据压缩。生成的InitialCreate文件似乎只创建了User Profile表,它的Story表代码中没有任何内容。

我将以下行添加到Global.asax

Database.SetInitializer(new Models.IntializeMySocialStoriesDb());

如果我现在更改模型,数据库上的任何内容都不会更改。如果我手动删除数据库并将InitializeMySocialStoriesDb更改为DropCreateDatabaseAlways然后运行应用程序,则不会创建数据库。

我只是想知道我错过了什么。

1 个答案:

答案 0 :(得分:2)

不要理会这种机制。这对于生产应用程序来说是不可行的,并且每次模式更改时都要求您填充所有数据。

而是将数据库架构创建为单独的SSDT项目,并使用DACPAC文件初始部署和升级生产数据库,同时保持所有数据的完整性。只需将SimpleMembership创建的表复制到您的SSDT项目中即可。

通过这种方式,您可以获得精确的列定义,可以准确定义约束,准确定义外键,主键和唯一键等,并仍然可以通过应用程序项目中的Entity Framework访问数据。升级生产数据库上的模式只需要部署DACPAC。

在开发过程中,当您在SSDT中进行更改时,Visual Studio将自动对表结构进行任何更改。

简而言之,我认为代码优先太松散,没有组织,也不是一个坏主意。

相关问题