1.在Model類里面,寫好相應的屬性。

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Data.Entity; 6
7 namespace MvcMovie.Models 8 { 9 public class Movie 10 { 11 public int ID { get; set; } 12 public string Title { get; set; } 13 public DateTime ReleaseDate { get; set; } 14 public string Genre { get; set; } 15 public decimal Price { get; set; } 16 } 17
18 public class MovieDBContext : DbContext 19 { 20 public DbSet<Movie> Movies { get; set; } 21 } 22 }
2.在配置文件中,寫上:

1 <add name="MovieDBContext"
2 connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
3 providerName="System.Data.SqlClient"/>
3.添加一個控制器,選擇剛才我們創建的Model作為模型(即創建強類型視圖)
4.這個時候,重新生成一下項目,就會在App_Data里面生成了一個數據庫(Movie.mdf).
Entity Framework Code First detected that the database connection string that was provided pointed to a Movies
database that didn’t exist yet, so Code First created the database automatically. 這句話的意思是:EF 代碼先行檢測到,數據庫的連接字符串,指向了一個Movie的數據庫,但是這個數據庫並不存在,所以code first自動為我們創建了這個數據庫。
5.You don't actually need to add the MovieDBContext
connection string. If you don't specify a connection string, Entity Framework will create a LocalDB database in the users directory with the fully qualified name of the DbContextclass (in this case MvcMovie.Models.MovieDBContext
). You can name the database anything you like, as long as it has the .MDF suffix. For example, we could name the database MyFilms.mdf.
這句話的大概意思是:你實際上不必添加我上面的字符串到webconifg文件中,因為EF會為我們按照用戶項目的物理路徑,創建一個全路徑的名稱的數據庫。如果你添加了連接字符串,EF就會按照你寫的,為你創建這個數據庫。
6.EF為我們創建的數據庫為:
可以看出,EF為我們創建的數據庫,string字段,默認是為空的。ID字段默認是主鍵。