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 Movie10 {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 : DbContext19 {20 public DbSet<Movie> Movies { get; set; }21 }22 }Movie
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 thatwas provided pointed to aMovies
database that didn’t exist yet, soCode First created the database automatically. 這句話的意思是:EF 代碼先行檢測到,數據庫的連接字符串,指向了一個Movie的數據庫,但是這個數據庫并不存在,所以code first自動為我們創建了這個數據庫。
5.You don't actually need to add theMovieDBContext
connection string. If you don't specify aconnection string, Entity Framework will create a LocalDB database in the usersdirectory with the fully qualified name of theDbContextclass (in this caseMvcMovie.Models.MovieDBContext
). You can name the database anything you like, as long as it has the.MDF suffix. For example, we could name the databaseMyFilms.mdf.
這句話的大概意思是:你實際上不必添加我上面的字符串到webconifg文件中,因為EF會為我們按照用戶項目的物理路徑,創建一個全路徑的名稱的數據庫。如果你添加了連接字符串,EF就會按照你寫的,為你創建這個數據庫。
6.EF為我們創建的數據庫為:
可以看出,EF為我們創建的數據庫,string字段,默認是為空的。ID字段默認是主鍵。
新聞熱點
疑難解答