EF Code First学习笔记 初识Code First
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)。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库