Mappings To Database
Model-wide Mapping
  • Set default Schema
  • Set Custom Convetions
Entity Mapping
  • To Single or Multiple Tables and Schema
  • To Complex type
  • Inheritance Hierarchies
Property Mapping
  • To Column, Column Name, Column Type, Nullable or Not Null Column, Column size, Columns Order
  • To Concurrency column
  • To Foreign key column
  • To configure relationships
public class SchoolContext: DbContext
{
public SchoolDBContext(): base()
{
} public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure domain classes using modelBuilder here base.OnModelCreating(modelBuilder);
}
}

在OnModelCreating方法中配置Fluent API

Code First配置优先顺序为:Fluent API > DataAnnotations > default conventions

EntityTypeConfiguration

EntityTypeConfiguration是一个重要的类,

Method Name Return Type Description
HasKey<TKey> EntityTypeConfiguration 为实体类配置主键
HasMany<TTargetEntity> ManyNavigationPropertyConfiguration 配置多对多的关系
HasOptional<TTargetEntity> OptionalNavigationPropertyConfiguration

配置从这个实体中可选的关系,这个实体的实例可以没有和关系就保存到数据库中,数据库中的外键可为nullable

HasRequired<TTargetEntity> RequiredNavigationPropertyConfiguration

配置从这个实体中必须的关系,实体的实例如果没有指定关系不能保存在数据库中,数据库外键为non-nullable

Ignore<TProperty> Void 排除实体的属性不映射到数据库中
Map EntityTypeConfiguration 允许与此实体类型映射到数据库架构的高级配置有关。
Property<T> StructuralTypeConfiguration 配置在该类型上定义的结构属性
ToTable Void 配置此实体类型映射到的表名。

Entity Mappings

public class Student
{
public Student()
{ }
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime? DateOfBirth { get; set; }
public byte[] Photo { get; set; }
public decimal Height { get; set; }
public float Weight { get; set; } public Standard Standard { get; set; }
} public class Standard
{
public Standard()
{ }
public int StandardId { get; set; }
public string StandardName { get; set; } public ICollection<Student> Students { get; set; } }

Configure Default Schema

public class SchoolContext: DbContext
{
public SchoolDBContext(): base()
{
} public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure default schema
modelBuilder.HasDefaultSchema("Admin");
}
}

配置实体映射到表

namespace CodeFirst_FluentAPI_Tutorials
{ public class SchoolContext: DbContext
{
public SchoolDBContext(): base()
{
} public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure default schema
modelBuilder.HasDefaultSchema("Admin"); //Map entity to table
modelBuilder.Entity<Student>().ToTable("StudentInfo");
modelBuilder.Entity<Standard>().ToTable("StandardInfo","dbo"); }
}
}

配置实体到多个表中

namespace CodeFirst_FluentAPI_Tutorials
{ public class SchoolContext: DbContext
{
public SchoolDBContext(): base()
{
} public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().Map(m =>
{
m.Properties(p => new { p.StudentId, p.StudentName});
m.ToTable("StudentInfo"); }).Map(m => {
m.Properties(p => new { p.StudentId, p.Height, p.Weight, p.Photo, p.DateOfBirth});
m.ToTable("StudentInfoDetail"); }); modelBuilder.Entity<Standard>().ToTable("StandardInfo"); }
}
}

Property Mappings

public class SchoolContext: DbContext
{
public SchoolDBContext(): base()
{
} public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure primary key
modelBuilder.Entity<Student>().HasKey<int>(s => s.StudentKey);
modelBuilder.Entity<Standard>().HasKey<int>(s => s.StandardKey); //Configure composite primary key
modelBuilder.Entity<Student>().HasKey<int>(s => new { s.StudentKey, s.StudentName });
}
}
public class SchoolContext: DbContext
{
public SchoolDBContext(): base()
{
} public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure Column
modelBuilder.Entity<Student>()
.Property(p => p.DateOfBirth)
.HasColumnName("DoB")
.HasColumnOrder()
.HasColumnType("datetime2");
}
}

配置nullable和non-nullable

namespace CodeFirst_FluentAPI_Tutorials
{ public class SchoolContext: DbContext
{
public SchoolDBContext(): base()
{
} public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure Null Column
modelBuilder.Entity<Student>()
.Property(p => p.Heigth)
.IsOptional(); //Configure NotNull Column
modelBuilder.Entity<Student>()
.Property(p => p.Weight)
.IsRequired();
}
}
}

配置列的长度

namespace CodeFirst_FluentAPI_Tutorials
{ public class SchoolContext: DbContext
{
public SchoolDBContext(): base()
{
} public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Set StudentName column size to 50
modelBuilder.Entity<Student>()
.Property(p => p.StudentName)
.HasMaxLength(); //Set StudentName column size to 50 and change datatype to nchar
//IsFixedLength() change datatype from nvarchar to nchar
modelBuilder.Entity<Student>()
.Property(p => p.StudentName)
.HasMaxLength().IsFixedLength(); //Set size decimal(2,2)
modelBuilder.Entity<Student>()
.Property(p => p.Height)
.HasPrecision(, );
}
}
}

配置并发列

namespace CodeFirst_FluentAPI_Tutorials
{ public class SchoolContext: DbContext
{
public SchoolDBContext(): base()
{
} public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Set StudentName as concurrency column
modelBuilder.Entity<Student>()
.Property(p => p.StudentName)
.IsConcurrencyToken();
}
}
}

也可以用IsRowVersion()来配置byte[]数组

EF Code-First 学习之旅 Fluent API的更多相关文章

  1. EF Code First教程-02.1 Fluent API约定配置

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  2. EF Code First 学习笔记:约定配置 Data Annotations+Fluent API

    要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一个就 ...

  3. Entity Framework 实体框架的形成之旅--Code First模式中使用 Fluent API 配置(6)

    在前面的随笔<Entity Framework 实体框架的形成之旅--Code First的框架设计(5)>里介绍了基于Code First模式的实体框架的经验,这种方式自动处理出来的模式 ...

  4. EF Code First学习笔记

    EF Code First学习笔记 初识Code First EF Code First 学习笔记:约定配置 Entity Framework 复杂类型 Entity Framework 数据生成选项 ...

  5. EF Code First学习系列

    EF Model First在实际工作中基本用不到,前段时间学了一下,大概的了解一下.现在开始学习Code First这种方式.这也是在实际工作中用到最多的方式. 下面先给出一些目录: 1.什么是Co ...

  6. ORM系列之二:EF(4) 约定、注释、Fluent API

    目录 1.前言 2.约定 2.1 主键约定 2.2 关系约定 2.3 复杂类型约定 3.数据注释 3.1 主键 3.2 必需 3.3 MaxLength和MinLength 3.4 NotMapped ...

  7. Entity Framework Code First (四)Fluent API - 配置属性/类型

    上篇博文说过当我们定义的类不能遵循约定(Conventions)的时候,Code First 提供了两种方式来配置你的类:DataAnnotations 和 Fluent API, 本文将关注 Flu ...

  8. EF Code First 学习笔记:表映射

    多个实体映射到一张表 Code First允许将多个实体映射到同一张表上,实体必须遵循如下规则: 实体必须是一对一关系 实体必须共享一个公共键 观察下面两个实体: public class Perso ...

  9. EF Code First 学习笔记:表映射 多个Entity到一张表和一个Entity到多张表

      多个实体映射到一张表 Code First允许将多个实体映射到同一张表上,实体必须遵循如下规则: 实体必须是一对一关系 实体必须共享一个公共键 观察下面两个实体: public class Per ...

随机推荐

  1. 高性能图片服务器–ZIMG(转)

    2011年李彦宏在百度联盟峰会上就提到过互联网的读图时代已经到来1,图片服务早已成为一个互联网应用中占比很大的部分,对图片的处理能力也相应地变成企业和开发者的一项基本技能.需要处理海量图片的典型应用有 ...

  2. shell脚本中出现^M

    在Windows中编辑的shell脚本,传到linux系统中,在末尾发现出现了很多^M字符 1.问题分析 在windows下使用notepad++写的脚本上传到Linux下,在使用vim编辑的时候我们 ...

  3. 《数据结构(C#语言描述)》

    本文转载自abatei,数据结构学了很多次,但是只是知道硬性的概念,现在专攻C#语言,对编程语言也有了更深的认识, 买一本C#的数据结构来看看,再一次加深对数据结构的学习,真是一件让人高兴的事. 当当 ...

  4. docker openvas

    https://hub.docker.com/r/mikesplain/openvas/ Requirements DockerPorts available: 443, 9390, 9391 Usa ...

  5. Java你不知道的那些事儿—Java隐藏特性

    转载自:http://www.cnblogs.com/lanxuezaipiao/p/3460373.html 每 种语言都很强大,不管你是像我一样的初学者还是有过N年项目经验的大神,总会有你不知道的 ...

  6. 插叙LTE-2

      LTE TDD与LTE FDD技术简介和比较 标签: 频分双工(FDD) 时分双工(TDD) LTE 摘要:UTRA 的长期演进(Long Term Evolution ,LTE) 技术存在LTE ...

  7. MySQL中redo日志

    重做日志用来实现事务的持久性,即ACID中的D,由两部分组成: 一是内存中的重做日志缓冲(redo log buffer)  易丢失 二是重做日志文件(redo log file) 持久的 InnoD ...

  8. 前端基础-html(1)

    写在前面: 前端               后端 C(client)        S(server) B(browser)      S(server) 以用户为出发点 一.web标准 1)web ...

  9. Latex技巧:LaTex插图命令includegraphics参数详解

    Latex插图的命令是\includegraphics[选项]{文件} 这里的选项在表 7.1, 7.2, 7.3 中列出. 因为 \includegraphics 不会结束 当前段落,所以它能够在文 ...

  10. php会话技术之Session用法

    php会话技术之Session用法举例. 本文原始链接:http://www.jbxue.com/article/8940.html1.创建session <?php     //创建sessi ...