EF Code First学习笔记 初识Code First

xiaoxiao2021-02-28  68

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属性,说明DestinationLodging是一对多的关系,因而在Lodgings表中生成了外键Destination_DestinationId保存对应的DestinationId。外键的命名默认是导航属性名(这里是Destination)_对应主表的主键(这里是DestinationId)。

如果我的文章对你有帮助,就点一下推荐吧.(*^__^*) 转载链接: http://www.cnblogs.com/Gyoung/archive/2013/01/17/2863145.html
转载请注明原文地址: https://www.6miu.com/read-1950197.html

最新回复(0)