Code First是Entity Framework提供的一種新的編程模型。通過Code First我們可以在還沒有建立數據庫的情況下就開始編碼,然后通過代碼來生成數據庫。
下面通過一個簡單的示例來了解。
建立一個控制台項目。通過Nuget來獲取Entity Framework。
增加兩個模型類:
public class Destination { public int DestinationId { get; set; } public string Name { get; set; } public string Country { get; set; } public string Description { get; set; } public byte[] Photo { get; set; } public List<Lodging> Lodgings { get; set; } } public class Lodging { public int LodgingId { get; set; } public string Name { get; set; } public string Owner { get; set; } public bool IsResort { get; set; } public Destination Destination { get; set; } }
再新增Context類:
public class BreakAwayContext : DbContext { public DbSet<Destination> Destinations { get; set; } public DbSet<Lodging> Lodgings { get; set; } }
在Main方法中加入下列代碼:
static void Main(string[] args) { var d = DateTime.Now.Date.ToString("yyyyMM"); var destination = new Destination { Country = "Indonesia", Description = "EcoTourism at its best in exquisite Bali", Name = "Bali" }; using (var context = new BreakAwayContext()) { context.Destinations.Add(destination); context.SaveChanges(); } Console.WriteLine("OK"); }
執行成功后打開數據庫,默認為.\SQLEXPRESS。
我們可以看到,新增了一個名為BreakAway.BreakAwayContext的數據庫。
[Destinations]表里面也插入了我們剛增加的記錄:
很COOL吧,Code First就是這么神奇。這里我們代碼里面什么也沒設置,都是Code First默認生成的。通過生成的數據庫庫我們來了解一下這些默認設置。
數據庫名:當沒有顯示設置數據連接的時候,默認的數據庫是:.\SQLEXPRESS。如果本地沒有SQLEXPRESS,EF會嘗試LocalDb ((localdb)\v11.0) .\SQLEXPRESS
這個數據庫包含在VS2012中。數據庫的名稱一般是DbContext的“命名空間.類名”,本例中是BreakAway.BreakAwayContext
表名:表名默認為模型類名的復數形式,並且每個表都使用dbo構架創建。這里生成的就是dbo.Lodgings.
主鍵:Code First會默認將以類似Id結尾來命名的屬性當作主鍵,如ID,Id,本例中的DestinationId都自動設置為主鍵。如果該屬性是int類型,Code First會在數據庫中默認將該列設置為自增長。
數據類型:在SQL Server中,字符串默認映射成nvarchar(max),byte[]映射成varbinary(max),bool映射成bit,decimal映射成decimal(18, 2),float映射成float。同時因為bool,decimal,float等是值類型,不能為給他們分配Null值。所生成的數據庫會要求對應的列非空。如Lodgings表中的IsResort
外鍵:Code First檢測到模型間有一對多的關系,會自動在相應表中生成外鍵。在這時,Code First檢測到Destination類中有一個List<Lodging> Lodgings屬性,而在Lodging類中有一個Destination Destination屬性,說明Destination與Lodging是一對多的關系,因而在Lodgings表中生成了外鍵Destination_DestinationId保存對應的DestinationId。外鍵的命名默認是導航屬性名(這里是Destination)_對應主表的主鍵(這里是DestinationId)。