我正在使用.NET Framework 4.6编写一个CMS项目,但一开始就遇到了问题。该项目有 3 层,数据层、领域层和 MVC 层是分开的。我用 Fluent 创建了表格。 一切似乎都很好并且运行没有错误,但是项目数据库没有创建。我还将提供该项目完整源代码的链接。如果有人知道这个问题,请告诉我。 github
总共需要创建三张表,项目的dbcontext和connectionstring如下:
public class CMSContext : DbContext
{
#region Constructor
public CMSContext() : base("CMS_DB") { }
#endregion
#region Tables
public DbSet<PageGroup> PageGroups { get; set; }
public DbSet<Page> Pages { get; set; }
public DbSet<PageComment> PageComments { get; set; }
#endregion
#region Fluent
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new PageMap());
modelBuilder.Configurations.Add(new PageGroupMap());
modelBuilder.Configurations.Add(new PageCommentMap());
}
#endregion
}
<connectionStrings>
<add name="CMS_DB" connectionString="Data Source=.;Initial Catalog=CMSProject_DB;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
迁移代码:
public override void Up()
{
CreateTable(
"Portal.Comments",
c => new
{
CommentId = c.Int(nullable: false, identity: true),
PageId = c.Int(nullable: false),
Name = c.String(nullable: false, maxLength: 150),
Email = c.String(maxLength: 200),
WebSite = c.String(maxLength: 200),
Comment = c.String(maxLength: 500),
CreateDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.CommentId)
.ForeignKey("Portal.Pages", t => t.PageId, cascadeDelete: true)
.Index(t => t.PageId);
CreateTable(
"Portal.Pages",
c => new
{
PageId = c.Int(nullable: false, identity: true),
GroupId = c.Int(nullable: false),
Title = c.String(nullable: false, maxLength: 350),
ShortDescription = c.String(nullable: false, maxLength: 250),
Text = c.String(nullable: false),
Visit = c.Int(nullable: false),
ImageName = c.String(),
ShowInSlider = c.Boolean(nullable: false),
CreateDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.PageId)
.ForeignKey("Portal.Groups", t => t.GroupId, cascadeDelete: true)
.Index(t => t.GroupId);
CreateTable(
"Portal.Groups",
c => new
{
GroupId = c.Int(nullable: false, identity: true),
GroupTitle = c.String(nullable: false, maxLength: 150),
})
.PrimaryKey(t => t.GroupId);
}
public override void Down()
{
DropForeignKey("Portal.Comments", "PageId", "Portal.Pages");
DropForeignKey("Portal.Pages", "GroupId", "Portal.Groups");
DropIndex("Portal.Pages", new[] { "GroupId" });
DropIndex("Portal.Comments", new[] { "PageId" });
DropTable("Portal.Groups");
DropTable("Portal.Pages");
DropTable("Portal.Comments");
}
尝试在重写中调用基本方法。
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}