我在Visual Studio 2015中启动ASP.NET Webforms应用程序,我正在尝试使用Entity Framework Code First将我的模型添加到数据库,但数据库文件未显示。我正在使用安装VS时出现的SQL Server Express LocalDB以简化操作。我设置了以下代码来创建和填充我的模型。
模特班"怪物":
using System.ComponentModel.DataAnnotations;
namespace MonsterMadness.Models
{
public class Monster
{
[ScaffoldColumn(false)]
public int MonsterId { get; set; }
public string Name { get; set; }
[ScaffoldColumn(false)]
public int AttackPower { get; set; }
[ScaffoldColumn(false)]
public int Defence { get; set; }
[ScaffoldColumn(false)]
public int ChanceToHit { get; set; }
[ScaffoldColumn(false)]
public int Dodge { get; set; }
[ScaffoldColumn(false)]
public int Critical { get; set; }
}
}
我的数据库上下文类" MonsterMadnessContext":
using System.Data.Entity;
namespace MonsterMadness.Models
{
public class MonsterMadnessContext : DbContext
{
public MonsterMadnessContext() : base("MonsterMadness")
{
}
public DbSet<Monster> Monsters
{
get; set;
}
}
}
我的初始化程序&#34; MonsterMadnessDatabaseInitializer&#34;:
using System.Data.Entity;
namespace MonsterMadness.Models
{
public class MonsterMadnessDatabaseInitializer : DropCreateDatabaseIfModelChanges<MonsterMadnessContext>
{
protected override void Seed(MonsterMadnessContext context)
{
GetMonsters().ForEach(monster => context.Monsters.Add(monster));
}
private static List<Monster> GetMonsters()
{
List<Monster> monsters = new List<Monster>
{
new Monster()
{
Name = "Test 1",
AttackPower = 10,
ChanceToHit = 10,
Critical = 10,
Defence = 10,
Dodge = 10
},
new Monster()
{
Name = "Test 2",
AttackPower = 20,
ChanceToHit = 20,
Critical = 20,
Defence = 20,
Dodge = 20
}
};
return monsters;
}
}
}
我的初始化程序在Global.ascx文件中运行:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//Initialize database
Database.SetInitializer(new MonsterMadnessDatabaseInitializer());
}
}
最后我的web.config条目为&#34; MonsterMadess&#34;应该指向LocalDB的连接字符串:
<connectionStrings>
<add name="MonsterMadness" connectionString="Data Source=(LocalDB)\v12.0;AttachDbFilename=|DataDirectory|\monstermadness.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
我根据this tutorial设置了所有内容,但每当我运行应用程序时,我都看不到正在创建的mdf文件。由于我运行了初始化程序,因此表中应该有数据并且应该创建文件。我错过了什么?谢谢你的帮助。
答案 0 :(得分:0)
将此行添加到上下文构造函数:
Database.SetInitializer(
new CreateDatabaseIfNotExists<MonsterMadnessContext>());