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. Bootstrap(Web前端CSS框架)

    官方定义: Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile fi ...

  2. PHP输出语句大杂烩

    一 echo echo() 实际上不是一个函数,是php语句,因此您无需对其使用括号.不过,如果您希望向 echo() 传递一个以上的参数,那么使用括号会发生解析错误.而且echo是返回void的,并 ...

  3. AtCoder Express(数学+二分)

    D - AtCoder Express Time limit : 2sec / Memory limit : 256MB Score : 400 points Problem Statement In ...

  4. $(document).ready() $(window).load 及js的window.onload

    1.$(document).ready()  简写为$(function(){}) DOM结构绘制完成执行,而无需等到图片或其他媒体下载完毕. 2.$(window).load  在有时候确实我们有需 ...

  5. 密码硬编码(Password Management: Hardcoded Password)

    在对项目进行安全扫描时,发现一些密码硬编码问题,本文主要三个方面:1)什么是密码硬编码:2)密码硬编码的危害:3)密码硬编码的解决方案. 一 什么是密码硬编码 将密码以明文的形式直接写到代码中,就是密 ...

  6. ffmpeg参数使用说明2

    附录一(ffmpeg参数说明): [参数] [说明] [示例] -i "路径" 指定需要转换的文件路径 -i "C:\nba.wmv" -y 覆盖输出文件,即如 ...

  7. unknown encoder libvpx

    brew install ffmpeg --with-libvpx or brew reinstall ffmpeg --with-libvpx

  8. 稀疏自动编码器 (Sparse Autoencoder)

    摘要: 一个新的系列,来自于斯坦福德深度学习在线课程:http://deeplearning.stanford.edu/wiki/index.php/UFLDL_Tutorial.本文梳理了该教程第一 ...

  9. 我的第三个Python小程序

    99乘法表: # Author: fansik # Description: 99 times table # method 1 num1 = 0 num2 = 0 while num1 < 9 ...

  10. 算法题16 贪吃的小Q 牛客网 腾讯笔试题

    算法题16 贪吃的小Q 牛客网 腾讯笔试题 题目: 链接:https://www.nowcoder.com/questionTerminal/d732267e73ce4918b61d9e3d0ddd9 ...