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的更多相关文章

  1. Entity Framework Code first(转载)

    一.Entity Framework Code first(代码优先)使用过程 1.1Entity Framework 代码优先简介 不得不提Entity Framework Code First这个 ...

  2. 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的无状态模 ...

  3. Entity Framework Code First (三)Data Annotations

    Entity Framework Code First 利用一种被称为约定(Conventions)优于配置(Configuration)的编程模式允许你使用自己的 domain classes 来表 ...

  4. Entity Framework Code First (二)Custom Conventions

    ---------------------------------------------------------------------------------------------------- ...

  5. Entity Framework Code First (一)Conventions

    Entity Framework 简言之就是一个ORM(Object-Relational Mapper)框架. Code First 使得你能够通过C#的类来描述一个模型,模型如何被发现/检测就是通 ...

  6. Entity Framework Code First (七)空间数据类型 Spatial Data Types

    声明:本文针对 EF5+, Visual Studio 2012+ 空间数据类型(Spatial Data Types)是在 EF5 中引入的,空间数据类型表现有两种: Geography (地理学上 ...

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

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

  8. Entity Framework Code First (八)迁移 Migrations

    创建初始模型和数据库 在开始使用迁移(Migrations)之前,我们需要一个 Project 和一个 Code First Model, 对于本文将使用典型的 Blog 和 Post 模型 创建一个 ...

  9. Entity Framework Code First (六)存储过程

    声明:本文只针对 EF6+ 默认情况下,Code First 对实体进行插入.更新.删除操作是直接在表上进行的,从 EF6 开始你可以选择使用存储过程(Stored Procedures) 简单实体映 ...

随机推荐

  1. python中reduce()函数

    reduce()函数也是Python内置的一个高阶函数.reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收 ...

  2. CSS3自定义Checkbox特效

    在线演示 本地下载

  3. ACM,我回来了!

    经过两天的时间,到了家一趟! 我终于又重新回到ACM实验室了!,有点头晕啊!!!

  4. iptables原理及使用教程

    注意 修改iptables可能导致连接断开, 对于远程连接的用户, 需要在经过充分测试后在修改, 对于懒人可以设置一个crontab, 在你修改iptables的过程中每隔30分钟清空一次iptabl ...

  5. 剑指offer之 整数中1出现的次数

    public class Solution { public int NumberOf1Between1AndN_Solution(int n) { int count=0; for(int i=1; ...

  6. Windows默认字符集_查询

    https://zhidao.baidu.com/question/32462047.html Windows95. XP……7操作系统自带的都是GBK字符集(含2万余汉字),是完全兼容GB2312( ...

  7. Python- and & or 的短路原则

    条件1 and 条件2 条件1 or 条件2 短路原则 对于and 如果前面的第一个条件为假,那么这个and前后两个条件组成的表达式的计算结果就一定为假,第二个条件就不会被计算 对于or 如果前面的第 ...

  8. C#统计目录中文件MD5值

    1. [代码]统计目录中文件MD5值 using System.IO;using System.Security.Cryptography;using System.Collections;using ...

  9. Delphi - 数组 详解

    技术交流,DH讲解. 首先我们要知道什么是数组?数组是一堆相同特性数据的一个集合,也就是每个元素的类型必须是一样的,当然在其他一些弱语法的语言里面,数组的元素可以千奇百怪. 例子: ? 1 2 3 4 ...

  10. 五 Django框架,models.py模块,数据库操作——表类容的增删改查

    Django框架,models.py模块,数据库操作——表类容的增删改查 增加数据 create()方法,增加数据 save()方法,写入数据 第一种方式 表类名称(字段=值) 需要save()方法, ...