我有上下文db类:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
namespace MvcApplication.Models {
public class PeopleContextDb : DbContext {
public PeopleContextDb() : base("PeopleContextDb") { }
public DbSet<Person> People { get; set; }
public DbSet<Meeting> Meetings { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
我有这个类(我有正确的命名空间):
using MvcApplication.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication.App_Start {
public class PeopleInitilizer : System.Data.Entity.DropCreateDatabaseIfModelChanges<PeopleContextDb> {
protected override void Seed(PeopleContextDb context) {
var people = new List<Person> {
new Person{FirstName = "John", LastName = "Doe", CellNumber = "123-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now, Pesel = "312312312", Notes = "Annoying"},
new Person{FirstName = "Anna", LastName = "Doe", CellNumber = "123-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now, Pesel = "548555672", Notes = "Less Annoying"}
};
people.ForEach(person => context.People.Add(person));
context.SaveChanges();
}
}
}
但是我的项目中还没有数据库如何生成一个?
我添加了连接字符串:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcApplication-20140710053828.mdf;Initial Catalog=aspnet-MvcApplication-20140710053828;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="PeopleContextDb" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
答案 0 :(得分:0)
您可以使用 Code First Migrations 技术使用Entity Framework创建和更新数据库文件。在将数据库部署到生产环境之前,这种使数据库与数据模型保持同步的方法很有效。
此过程涉及三个步骤,您已经完成了第一个步骤:
有两篇关于Code First Migration方法的好文章,您可以从以下链接中找到:
Code First Migrations and Deployment with the Entity Framework in an ASP.NET MVC Application