[英]ASP.NET MVC Entity Framework Database not being created
I am trying to build a phonebook in ASP.NET MVC using Entity Framework but my code is not generating the database: 我试图使用Entity Framework在ASP.NET MVC中构建电话簿,但是我的代码未生成数据库:
I have the following classes: 我有以下课程:
Contact.cs Contact.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; }
}
PhoneType.cs PhoneType.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 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 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);
}
}
In Web.config I have the following: 在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" />
When I run the application, the database files are not being created. 运行应用程序时,未创建数据库文件。
Can you please help me out. 你能帮我一下吗。
Thanks! 谢谢!
I figured out the answer. 我想出了答案。 The program didn't like that I was using "type" in the PhoneType class.
该程序不喜欢我在PhoneType类中使用“类型”。 And also I changed the way I seeded the data to
而且我还更改了将数据播种到的方式
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.