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 3 软件开发规范

    Python 3 软件开发规范 参考链接 http://www.cnblogs.com/linhaifeng/articles/6379069.html#_label14 对每个目录,文件介绍. #= ...

  2. Luogu-4196 [CQOI2006]凸多边形

    凸多边形的面积就相当于半平面交 求几个凸多边形面积交就相当于一堆半平面一起求交 #include<cmath> #include<cstdio> #include<cst ...

  3. EntityFramework 学习 一 DBEntityEntry

    DbEntityEntry是一个重要的类,用来获取各种各样的实体信息 可以通过DBContext的Entry方法获取DbEntityEntry的实例 DBEntityEntry studentEntr ...

  4. wget下载文件

    http://blog.sina.com.cn/s/blog_4af3f0d20100n1k0.html 一.下载目录 #wget -r -np -nd http://example.com/pack ...

  5. Storm- 使用Storm实现词频汇总

    需求:读取指定目录的数据,并实现单词计数的功能 实现方案: Spout来读取指定目录的数据,作为后续Bolt处理的input 使用一个Bolt把input 的数据,切割分开,我们按照逗号进分割 使用一 ...

  6. R 语言实现求导

    前言 高等数学是每个大学生都要学习的一门数学基础课,同时也可能是考完试后最容易忘记的一门知识.我在学习高数的时候绞尽脑汁,但始终都不知道为何而学.生活和工作基本用不到,就算是在计算机行业和金融行业,能 ...

  7. Ueditor--toolbars

    (1)代码中定义 <script id="container" name="content" type="text/plain"> ...

  8. SpringBoot_03_依赖本地jar

    一.方法一 1.说明 用Maven打到本地仓库,然后直接引入 2.参考资料 Springboot 打Jar包,Maven完美解决本地Jar包自动打入Springboot Jar包中 3.执行maven ...

  9. Tomcat_异常_02_IOException while loading persisted sessions: java.io.EOFException

    异常原因: EOFException表示输入过程中意外地到达文件尾或流尾的信号,导致从session中获取数据失败. 这是由于tomcat上次非正常关闭时有一些活动session被持久化(表现为一些临 ...

  10. Java---变量与常量

    Java中的关键字 Java 语言中有一些具有特殊用途的词被称为关键字.关键字对 Java 的编译器有着特殊的意义,在程序中应用时一定要慎重 Java标识符 标识符就是用于给 Java 程序中变量.类 ...