以下是书《Programming Entity Framework Code First》的学习整理,主要是一个整体梳理。

一、模型属性映射约定

1.通过 System.Component  Model.DataAnnotations 来配置
  1. class AnimalType
  2. {
  3. public int Id { get; set; }
  4. [Required]
  5. public string TypeName { get; set; }
  6. }
意味着TypeName在数据库中的字段为not null。第二个是EntityFramework会对这个模型进行验证。比如在Savechanges的时候,模型的这个属性不能为空,否则会抛出异常。
  1. [Table("Species")]
  2. class AnimalType
  3. {
  4. public int Id { get; set; }
  5. [Required]
  6. public string TypeName { get; set; }
  7. }
像Table这个特性 意味着AnimalType对象在数据库映射到表Species上。
 
2.通过Fluent API来配置模型。
 通过Dbcontext的OnModelCreating来对模型进行配置。
  1. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  2. {
  3. modelBuilder.Entity<AnimalType>().ToTable("Animal");
  4. modelBuilder.Entity<AnimalType>().Property(p => p.TypeName).IsRequired();
  5. }
这样得到同样的效果。开发者一般倾向于使用API的方式来约定模型,这样保持class干净,而且API支持映射更多。API在特性后面执行,同样的代码(比如API是.HasMaxLength(300),特性是 [MaxLength(200)],数据库会是300的长度),API会覆盖特性。
如果你有很多属性需要约定,可以单独出来。继承EntityTypeConfiguration。
  1. public class DestinationConfiguration :
  2. EntityTypeConfiguration<Destination>
  3. {
  4. public DestinationConfiguration()
  5. {
  6. Property(d => d.Name).IsRequired();
  7. Property(d => d.Description).HasMaxLength();
  8. Property(d => d.Photo).HasColumnType("image");
  9. }
  10. }
  11. public class LodgingConfiguration :
  12. EntityTypeConfiguration<Lodging>
  13. {
  14. public LodgingConfiguration()
  15. {
  16. Property(l => l.Name).IsRequired().HasMaxLength();
  17. }
  18. }

然后再OnModelCreating中加进去,这个和modelBuilder.Entity<AnimalType>() 是同样的效果,modelBuilder.Entity<AnimalType>()会创建一个EntityTypeConfiguration。所以本质上他们是一样的代码。

  1. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  2. {
  3. modelBuilder.Configurations.Add(new DestinationConfiguration());
  4. modelBuilder.Configurations.Add(new LodgingConfiguration());
  5. }
最好先支持数据迁移,不然模型改变会触发异常。
  1. public class VetContext:DbContext
  2. {
  3. public DbSet<Patient> Patients { get; set; }
  4. public DbSet<Visit> Visits { get; set; }
  5.  
  6. public VetContext() : base("DefaultConnection")
  7. {
  8. Database.SetInitializer(new MigrateDatabaseToLatestVersion<VetContext, Configuration<VetContext>>());
  9. }
  10.  
  11. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  12. {
  13. modelBuilder.Entity<AnimalType>().ToTable("Animal");
  14. modelBuilder.Entity<AnimalType>().Property(p => p.TypeName).IsRequired();
  15. }
  16.  
  17. }
  18.  
  19. internal sealed class Configuration<TContext> : DbMigrationsConfiguration<TContext> where TContext : DbContext
  20. {
  21. public Configuration()
  22. {
  23. AutomaticMigrationsEnabled = true;
  24. AutomaticMigrationDataLossAllowed = true;
  25. }
  26. }
http://www.cnblogs.com/libingql/p/3352058.html 这个博客讲的很详细。
 
什么是Fluent API?
这个概念不是EF或者Code First专有的,指的就是使用链式方法的API,每个调用的返回类型都为下一个调用定义了有效方法。
 
二、模型关系映射约定---在Console 中使用EF
 
Dbcontext的初始化功能是很强大的。我们新建一个Console工程,加入下面的模型和BreakAwayContext.cs Destination和Lodging是一对多的关系。
  1. namespace Model
  2. {
  3. public class Destination
  4. {
  5. public int DestinationId { get; set; }
  6. public string Name { get; set; }
  7. public string Country { get; set; }
  8. public string Description { get; set; }
  9. public byte[] Photo { get; set; }
  10. public List<Lodging> Lodgings { get; set; }
  11. }
  12. }
  13. namespace Model
  14. {
  15. public class Lodging
  16. {
  17. public int LodgingId { get; set; }
  18. public string Name { get; set; }
  19. public string Owner { get; set; }
  20. public bool IsResort { get; set; }
  21. public Destination Destination { get; set; }
  22. }
  23. }
  24. namespace DataAccess
  25. {
  26. public class BreakAwayContext : DbContext
  27. {
  28. public DbSet<Destination> Destinations { get; set; }
  29. public DbSet<Lodging> Lodgings { get; set; }
  30. }
  31. }

运行主程序:

  1. private static void InsertDestination()
  2. {
  3. var destination = new Destination
  4. {
  5. Country = "Indonesia",
  6. Description = "EcoTourism at its best in exquisite Bali",
  7. Name = "Bali"
  8. };
  9. using (var context = new BreakAwayContext())
  10. {
  11. context.Destinations.Add(destination);
  12. context.SaveChanges();
  13. }
  14. }
  15. static void Main()
  16. {
  17. InsertDestination();
  18. }

我们在SQL Server资源管理器中可以找到这个数据库(书中说,他会自动早本机SQL Server Express中创建数据库,但是我安装的是Sql Server 2008 R2,在2008中没有找到新生成的数据库)。

而这个数据库的位置是在用户文件夹下面。右键点击ConsoleEf.BreakAwayContext 选择属性。

EF会自动的在数据表中创建主外键,并根据模型的属性的不同类型创建了不同的字段。我们再可以加一些属性约定,来限制数据库中字段的大小(注意图中的nvarchar(max)...)。修改一下Destination。

  1. public class Destination
  2. {
  3. public int DestinationId { get; set; }
  4. [Required]
  5. public string Name { get; set; }
  6. public string Country { get; set; }
  7. [MaxLength()]
  8. public string Description { get; set; }
  9. [Column(TypeName="image")]
  10. public byte[] Photo { get; set; }
  11. public List<Lodging> Lodgings { get; set; }
  12. }

模型改变在默认状态下回触发异常,Codefirst 有几种初始化的方法。CreateDatabaseIfNotExists ,DropCreateDatabaseIfModelchanges。我们选用模型改变时删除再重建数据库。

  1. static void Main(string[] args)
  2. {
  3. Database.SetInitializer(
  4. new DropCreateDatabaseIfModelChanges<BreakAwayContext>());
  5. InsertDestination();
  6. }

再次运行,数据库已经发生改变(第一次运行出现错误,提示数据库正在使用无法删除,我在进程中删除了sqlserver.exe运行才正常),但之前的数据已经不存在了,还是数据迁移的方法最好了,EF应该把这个设置成默认功能。

 
 
 
 
 

【读书笔记】Programming Entity Framework CodeFirst -- 初步认识的更多相关文章

  1. Programming Entity Framework CodeFirst -- 约定和属性配置

     以下是EF中Data Annotation和 Fluenlt API的不同属性约定的对照.   Length Data Annotation MinLength(nn) MaxLength(nn) ...

  2. 第三篇:Entity Framework CodeFirst & Model 映射 续篇 EntityFramework Power Tools 工具使用

    上一篇 第二篇:Entity Framework CodeFirst & Model 映射 主要介绍以Fluent API来实作EntityFramework CodeFirst,得到了大家一 ...

  3. ADO.NET Entity Framework CodeFirst 如何输出日志(EF 5.0)

    ADO.NET Entity Framework CodeFirst 如何输出日志(EF4.3) 用的EFProviderWrappers ,这个组件好久没有更新了,对于SQL执行日志的解决方案的需求 ...

  4. 第二篇:Entity Framework CodeFirst & Model 映射

    前一篇 第一篇:Entity Framework 简介 我有讲到,ORM 最关键的 Mapping,也提到了最早实现Mapping的技术,就是 特性 + 反射,那Entity Framework 实现 ...

  5. Programming Entity Framework 翻译(2)-目录2-章节

    How This Book Is Organized 本书组织结构 Programming Entity Framework, Second Edition, focuses on two ways ...

  6. Programming Entity Framework 翻译

    刚开始接触.net,c#语法应该说还没掌握好.学习实践的旅程就从linq和EF开始吧.感觉相比之前的开发方式,linq和EF方便好多. linq入门用了好久,因为c#不行,补习了2.0的泛型,3.0和 ...

  7. Entity Framework CodeFirst数据迁移

    前言 紧接着前面一篇博文Entity Framework CodeFirst尝试. 我们知道无论是“Database First”还是“Model First”当模型发生改变了都可以通过Visual ...

  8. [Programming Entity Framework] 第3章 查询实体数据模型(EDM)(一)

    http://www.cnblogs.com/sansi/archive/2012/10/18/2729337.html Programming Entity Framework 第二版翻译索引 你可 ...

  9. entity framework codefirst 用户代码未处理DataException,InnerException基础提供程序在open上失败,数据库生成失败

    警告:这是一个入门级日志,如果你很了解CodeFirst,那请绕道 背景:这篇日志记录我使用Entity FrameWork CodeFirst时出现的错误和解决问题的过程,虽然有点曲折……勿喷 备注 ...

随机推荐

  1. 强大的Spring缓存技术(上)

    缓存是实际工作中非常常用的一种提高性能的方法, 我们会在许多场景下来使用缓存. 本文通过一个简单的例子进行展开,通过对比我们原来的自定义缓存和 spring 的基于注释的 cache 配置方法,展现了 ...

  2. tkinter 在 x window 下的字体设置格式

    X Font Descriptors # X Font Descriptors are strings having the following format (the asterisks repre ...

  3. 危险的“我以为”DDoS&丑陋的现实

    有些话题可能终其一生你也可以假装不知道就好了,比如全球气候在变暖,不过有些话题确是不得不面对的冰冷现实,在互联网日益发达的当下,比如你不得不面对的DDoS攻击. DDoS代表了分布式拒绝服务,通过许多 ...

  4. 当我我们用new操作符创建对象的时候,都发生了些什么?

    //下面这段代码是javascript设计模式与开发实践上的一段代码 function Person( name ){            this.name = name;        };   ...

  5. CSS总则。

    2.23:字体常用Css样式. font-family,font-size,color,font-weight,line-height,letter-spacing,text-decoration,t ...

  6. OD使用教程3

    reverseMe爆破: 跳转指令 让跳转已实现,把z的1改成0 按F8走,继续把z的1改成0,实现跳转 根据跳转指令,改变s或o,使跳转不实现 指令如上使跳转不实现 继续按f8往下走然后成功  

  7. windows下监测tomcat7内存使用情况

    在conf里面的server-user文件里添加 <tomcat-users> <role rolename="admin-gui"/> <user ...

  8. UVa 11292 Dragon of Loowater

    简单贪心 龙头的直径和人的佣金排序,价值小的人和直径小的配 #include<iostream> #include<cstdio> #include<cmath> ...

  9. 使用Wireshark 查看查找未被过滤端口

    打开Wireshark ,过滤输入“ip.src == [IP] && ip.ttl < 255”,因为防火墙伪造的数据包的TTL都是255,真实的数据包应该是56,所以这句话直 ...

  10. android 的闪屏效果

    android的闪屏效果,就是我们刚开始启动应用的时候弹出的界面或者动画,过2秒之后自动的跳转到主界面. 其实,实现这个效果很简单,使用Handler对象的postDelayed方法就可以实现.在这个 ...