Entity Framework Code-First(10.3):Property Mappings
Property Mappings using Fluent API:
Here, we will learn how to configure properties of an entity class using Fluent API.
We will use the following Student and Standard domain classes of our school application.
public class Student
{
public Student()
{ }
public int StudentKey { 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 StandardKey { get; set; }
public string StandardName { get; set; } public ICollection<Student> Students { get; set; } }
Configure Primary Key and Composite Primary key:
Our domain classes above, do not follow the Code-First convention for primary key because they don't have Id or {Class Name} + Id property. So, you can configure a key property using HasKey() method of EntityTypeConfiguration using Fluent API as below. RemembermodelBuilder.Entity<TEntity>()
returns EntityTypeConfiguration object.
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 });
}
}
Configure Column Name, Type and Order:
Default Code-First convention creates a column for a property with the same name, order, and datatype. You can override this convention, as shown below.
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");
}
}
As you can see in the above example, we used the Property() method to configure anything for a property of an entity. Here, we use HasColumnName to change the column name of DateOfBirth property. Also, we call HasColumnOrder and HasColumnType to change the order and datatype of a column.
modelBuilder.Entity<TEntity>().Property(expression)
allows you to use different methods to configure a particular property, as shown below.
Configure Null or NotNull column for a property:
Code-First will create NotNull column for a primitive data type property because primitive data type can not be null unless it is marked as nullable using ? sign or Nullable<T>.
Use IsOptional method to create a nullable column for a property. In the same way, use IsRequired method to create a NotNull column.
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();
}
}
}
Configure Column Size:
Code-First will set the maximum size of a data type for a column. You can override this convention, as shown below.
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(, );
}
}
}
As you can see in the above example, we used HasMaxLength method to set the size of a column. IsFixedLength method converts nvarchar to nchar type. In the same way, HasPrecision method changed the precision of the decimal column.
Configure Concurrency Column:
You can configure a property as concurrency column using ConcurrencyToken method, as shown below.
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();
}
}
}
As you can see in the above example, we set StudentName column as concurrency column so that it will be included in the where clause in update and delete commands.
You can also use IsRowVersion() method for byte[] property to make it as a concurrency column.
Entity Framework Code-First(10.3):Property Mappings的更多相关文章
- Entity Framework Code first(转载)
一.Entity Framework Code first(代码优先)使用过程 1.1Entity Framework 代码优先简介 不得不提Entity Framework Code First这个 ...
- ASP.NET MVC深入浅出系列(持续更新) ORM系列之Entity FrameWork详解(持续更新) 第十六节:语法总结(3)(C#6.0和C#7.0新语法) 第三节:深度剖析各类数据结构(Array、List、Queue、Stack)及线程安全问题和yeild关键字 各种通讯连接方式 设计模式篇 第十二节: 总结Quartz.Net几种部署模式(IIS、Exe、服务部署【借
ASP.NET MVC深入浅出系列(持续更新) 一. ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态模 ...
- Entity Framework Code First (三)Data Annotations
Entity Framework Code First 利用一种被称为约定(Conventions)优于配置(Configuration)的编程模式允许你使用自己的 domain classes 来表 ...
- Entity Framework Code First (二)Custom Conventions
---------------------------------------------------------------------------------------------------- ...
- Entity Framework Code First (一)Conventions
Entity Framework 简言之就是一个ORM(Object-Relational Mapper)框架. Code First 使得你能够通过C#的类来描述一个模型,模型如何被发现/检测就是通 ...
- Entity Framework Code First (七)空间数据类型 Spatial Data Types
声明:本文针对 EF5+, Visual Studio 2012+ 空间数据类型(Spatial Data Types)是在 EF5 中引入的,空间数据类型表现有两种: Geography (地理学上 ...
- Entity Framework Code First (四)Fluent API - 配置属性/类型
上篇博文说过当我们定义的类不能遵循约定(Conventions)的时候,Code First 提供了两种方式来配置你的类:DataAnnotations 和 Fluent API, 本文将关注 Flu ...
- Entity Framework Code First (八)迁移 Migrations
创建初始模型和数据库 在开始使用迁移(Migrations)之前,我们需要一个 Project 和一个 Code First Model, 对于本文将使用典型的 Blog 和 Post 模型 创建一个 ...
- Entity Framework Code First (六)存储过程
声明:本文只针对 EF6+ 默认情况下,Code First 对实体进行插入.更新.删除操作是直接在表上进行的,从 EF6 开始你可以选择使用存储过程(Stored Procedures) 简单实体映 ...
随机推荐
- html转义字符及css清除
1. [代码][Java]代码 import java.util.HashMap;import java.util.Map; import org.apache.commons.lang3. ...
- angularjs 系列之$q和promise
还是同一个项目,在项目中,发现多个controller之内有一个共同的服务器请求,当时只是不断的重复使用,如今,现在项目结束,代码开始走向了优化迭代的阶段: 首先,我的思路是把这个共同的请求,从con ...
- Linux课程---6、别名管理和网络配置(Linux命令如何记)
Linux课程---6.别名管理和网络配置(Linux命令如何记) 一.总结 一句话总结: 理解记忆:因为命令要实现那么多功能,必须有那么多参数,而不同的参数就适用不用的情况 命令基本格式:命令关键字 ...
- Shiro身份认证---转
目录 1. Shro的概念 2. Shiro的简单身份认证实现 3. Shiro与spring对身份认证的实现 前言: Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在 JavaSE 环境 ...
- python 特征选择 绘图 + mine
demo代码: # _*_coding:UTF-8_*_ import numpy as np import sys import pandas as pd from pandas import Se ...
- Javascript-- jQuery事件篇(3)
on()的多事件绑定 之前学的鼠标事件,表单事件与键盘事件都有个特点,就是直接给元素绑定一个处理函数,所有这类事件都是属于快捷处理.翻开源码其实可以看到,所有的快捷事件在底层的处理都是通过一个&quo ...
- 使用命令行生成 APNG 图片
使用 apngasm 工具 下载地址 https://sourceforge.net/projects/apngasm/files/2.91/ 本地源码编译 make 或者 下载对应环境的可执行程序 ...
- C语言小程序(五)、数组查询
随机产生一些字符,然后输入要查找的字符,本想将查找到的字符存储起来,要么初始化一个等大小的数组,要么要先检索出总共查找到多少个元素,再开辟空间存储,但这样相当于搜索了两遍,没有想到更好的方法,只是简单 ...
- H264 NALU 使用PS封装 RTP发送
最近由于项目平台需求,要将H264 NALU封装为PS再用RTP发送,PS封装按照ISO DEC-13818-1标准.一个PS包包含PS Header, PES Header, PS system h ...
- 在YUV图像上根据背景色实现OSD反色
所谓的OSD其实就是在视频图像上叠加一些字符信息,比如时间,地点,通道号等, 在图像上叠加OSD通常有两种方式: 一种是在前端嵌入式设备上,在图像数据上叠加OSD, 这样客户端这边只需解码显示数据即可 ...