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

一、模型属性映射约定

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

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

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new DestinationConfiguration());
modelBuilder.Configurations.Add(new LodgingConfiguration());
}
最好先支持数据迁移,不然模型改变会触发异常。
  public class VetContext:DbContext
{
public DbSet<Patient> Patients { get; set; }
public DbSet<Visit> Visits { get; set; } public VetContext() : base("DefaultConnection")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<VetContext, Configuration<VetContext>>());
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<AnimalType>().ToTable("Animal");
modelBuilder.Entity<AnimalType>().Property(p => p.TypeName).IsRequired();
} } internal sealed class Configuration<TContext> : DbMigrationsConfiguration<TContext> where TContext : DbContext
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
}
http://www.cnblogs.com/libingql/p/3352058.html 这个博客讲的很详细。
 
什么是Fluent API?
这个概念不是EF或者Code First专有的,指的就是使用链式方法的API,每个调用的返回类型都为下一个调用定义了有效方法。
 
二、模型关系映射约定---在Console 中使用EF
 
Dbcontext的初始化功能是很强大的。我们新建一个Console工程,加入下面的模型和BreakAwayContext.cs Destination和Lodging是一对多的关系。
namespace Model
{
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; }
}
}
namespace Model
{
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; }
}
}
namespace DataAccess
{
public class BreakAwayContext : DbContext
{
public DbSet<Destination> Destinations { get; set; }
public DbSet<Lodging> Lodgings { get; set; }
}
}

运行主程序:

private static void InsertDestination()
{
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();
}
}
static void Main()
{
InsertDestination();
}

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

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

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

public class Destination
{
public int DestinationId { get; set; }
[Required]
public string Name { get; set; }
public string Country { get; set; }
[MaxLength()]
public string Description { get; set; }
[Column(TypeName="image")]
public byte[] Photo { get; set; }
public List<Lodging> Lodgings { get; set; }
}

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

static void Main(string[] args)
{
Database.SetInitializer(
new DropCreateDatabaseIfModelChanges<BreakAwayContext>());
InsertDestination();
}

再次运行,数据库已经发生改变(第一次运行出现错误,提示数据库正在使用无法删除,我在进程中删除了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. 2. Abstract Factory(抽象工厂)

    意图: 提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类. 适用性: 一个系统要独立于它的产品的创建.组合和表示时. 一个系统要由多个产品系列中的一个来配置时. 当你要强调一系列相关 ...

  2. Android应用第一次安装成功点击“打开”后Home键切出应用后再点击桌面图标返回导致应用重启问题

    最近项目中遇到一个问题,用户第一次安装应用在系统的安装器安装完成界面有“完成”和“打开”两个按钮. 当用户点击“打开”按钮进入用户注册页面进行手机号验证码发送和验证码输入等操作界面,若此时用户点击Ho ...

  3. hdu 1142(DFS+dijkstra)

    #include<iostream> #include<cstdio> #include<cmath> #include<map> #include&l ...

  4. pragma

    在所有的预处理指令中,#pragma指令可能是最复杂的了,它的作用是设定编译器的状态或者是指示编译器完成一些特定的动作.#pragma指令对每个 编译器给出了一个方法,在保持与C和C++语言完全兼容的 ...

  5. Java中的equals和hashCode方法

    本文转载自:Java中的equals和hashCode方法详解 Java中的equals方法和hashCode方法是Object中的,所以每个对象都是有这两个方法的,有时候我们需要实现特定需求,可能要 ...

  6. Good-Bye

    嘛……以一种奇怪的姿势滚粗了…… 如果这个Blog能给未来的OIer们一些帮助的话,它也不枉存在了…… 我的OI之路也能以另一种形式延续下去吧…… 也许能搞ACM的话会再开?…… 不管怎么说,各位再见 ...

  7. Sql Server插入数据并返回自增ID,@@IDENTITY,SCOPE_IDENTITY和IDENT_CURRENT的区别

    预备知识:SQLServer的IDENTITY关键字IDENTITY关键字代表的是一个函数,而不是identity属性.在access里边没有这个函数,所以在access不能用这个语句.语法:iden ...

  8. Devexpress 汉化

    DevExpress是一个比较有名的界面控件套件,提供了一系列的界面控件套件的DotNet界面控件.对于较老的版本(例如之前项目中遇到的dev9),对于汉化(应该说本地化Localization)支持 ...

  9. permutation II (boss出来了)

    题目链接:https://leetcode.com/submissions/detail/55876321/ 自己的做法,30个测试用例通过了29例,终究还是有一个系列类型的是无法通过的,因为自己妄想 ...

  10. 超级编辑器--VIM的常见操作

    如下,都是我常用的 删除单词:  d + w 关闭vim窗口:   :q   或者 shift + zz 全部向左移: shift + v  --->  shift + <   ---&g ...