1、加入数据库连接代码
<add name="MovieDBContext" connectionString="Data Source=|DataDirectory|Movies.sdf" providerName="System.Data.SqlServerCe.4.0"/>
2、添加初始化的基础数据
MovieInitializer.cs
public class MovieInitializer:DropCreateDatabaseIfModelChanges<MovieDBContext> {
protected override void Seed(MoviDBContext context)
{
var movies=new List<Movie>
{
new Movie{Title="When Haary",ReleaseData=DateTime.Parse("2012-12-10"),Genre="Romantic",Rate="R",Price=90M},
new Movie{Title="wswabc",ReleaseData=DateTime.Parse("2090-20-09"),Genre="Asofo",Rate="B",Price=90M}
};
movies.ForEach(d=>context.Movies.Add(d));
} }
3、修改Global.asax.cs
using System.Data.Entity; using MvcMovie.Models
……………………
protected void Application_Start()
{
Database.SetInitializer<MovieDBContext>(new MovieInitializer());
..........
}
4、添加Movie.cs类
Public class MovieDBContext:DbContext { public DbSet<Movie> Movies{get;set;} } public class Movie { public string Title{get;set;} public DateTime ReleaseDate{get;set;} public string Genre{get;set;} }
5、添加"MoviesController.cs
public MoviesController:Controller { private MovieDBContext db=new MovieDBContext(); public ViewResult Index() { return View(db.Movies.ToList()); } ...................... }