我正在尝试使用实体框架在 ASP.NET MVC 中构建电话簿,但我的代码没有生成数据库:
我有以下课程:
联系人.cs
public class Contact
{
[Key]
public int id { get; set; }
public String fName { get; set; }
public String lName { get; set; }
public String phoneNumber { get; set; }
public PhoneType phoneType { get; set; }
}
电话类型.cs
public class PhoneType
{
[Key]
public int id { get; set; }
public String type { get; set; }
public ICollection<Contact> Contacts { get; set; } = new List<Contact>();
}
ContactDbContext.cs
public class ContactDbContext : DbContext
{
public ContactDbContext() : base("name=ContactDbContextConnectionString")
{
Database.SetInitializer<ContactDbContext>(new ContactDbInitializer());
}
public DbSet<Contact> Contacts { get; set; }
public DbSet<PhoneType> PhoneTypes { get; set; }
}
ContactDbInitializer.cs
public class ContactDbInitializer : DropCreateDatabaseAlways<ContactDbContext>
{
protected override void Seed(ContactDbContext context)
{
Contact a = new Contact()
{
fName = "Andra",
lName = "Avram",
phoneNumber = "604-788-5659"
};
a.phoneType.type = "cell";
context.Contacts.Add(a);
context.SaveChanges();
base.Seed(context);
}
}
在 Web.config 我有以下内容:
<connectionStrings>
<add name="ContactDbContextConnectionString" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=PhonebookDb;Integrated Security=true" providerName="System.Data.SqlClient" />
<add name="DefaultConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=phonebookContext-20180621103305; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|phonebookContext-20180621103305.mdf"
providerName="System.Data.SqlClient" />
当我运行应用程序时,没有创建数据库文件。
你能帮帮我吗?
谢谢!