ASP.NET 未创建 MVC 实体框架数据库



我正在尝试使用实体框架在 MVC 中构建电话簿 ASP.NET 但我的代码没有生成数据库:

我有以下课程:

联系方式.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" />

运行应用程序时,未创建数据库文件。

你能帮帮我吗?

谢谢!

我想出了答案。该程序不喜欢我在PhoneType类中使用"type"。而且我还更改了将数据播种的方式

PhoneType a = new PhoneType()
{
phoneType = "cell"
};
a.Contacts.Add(new Contact()
{
fName = "Andra",
lName = "Avram",
phoneNumber = "438-881-5659"
});
context.PhoneTypes.Add(a);
context.SaveChanges();
base.Seed(context);

最新更新