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) 简单实体映 ...
随机推荐
- P3214 [HNOI2011]卡农
题目 P3214 [HNOI2011]卡农 在被一题容斥\(dp\)完虐之后,打算做一做集合容斥这类的题了 第一次深感HNOI的毒瘤(题做得太少了!!) 做法 求\([1,n]\)组成的集合中选\(m ...
- POJ Layout
A - Layout Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u Submit S ...
- bootstraptable的 showFooter属性
如果想在表格最下面显示统计的信息可以使用这个属性 首先 先在表格加上这个属性 showFooter:true, 然后 在需要的列里面新增属性 footerFormatter 设置列的名称 然后在需 ...
- unity3D实现多点触碰
实现多点触碰是利用input这个类里面的方法实现的. 从edit-project settings-input就可以看到input能够得到的轴. 想要读取轴向可以使用Input.GetAxis方法获取 ...
- 【Selenium】Option加载用户配置,Chrom命令行参数
about:version - 显示当前版本 about:memory - 显示本机浏览器内存使用状况 about:plugins - 显示已安装插件 about:histograms - 显示历史记 ...
- WCF寄宿(Host)之自我寄宿(Self-Hosting)简单实例【Console应用为宿主】
前言: 由于最近的项目 中需要用到WCF,所以又回头翻了翻,阅读了大量园中大神的博文,故而做个总结. 谬误之处,万望不吝指教! 闲话不叙! 一.寄宿(Host)WCF服务 1)一种是为一组WCF服务 ...
- Linux下重命名文件或文件夹(mv命令与rename命令)
在Linux下重命名文件或目录,可以使用mv命令或rename命令 mv ———————————— mv命令既可以重命名,又可以移动文件或文件夹. 例子:将目录A重命名为B mv A B 例子:将/a ...
- appium-环境搭建(三)
appium步骤:基本环境1.由于操作手机端操作,需要模拟器或者真机 itools模拟器,真机2.appium操作app,需要知道操作的app是什么?需要知道这个app包名 1.问开发 2.利用adt ...
- 【集成学习】lightgbm参数介绍(sklearn)
# XGBoost和LightGBM部分参数对比表: lightgbm.sklearn参数介绍(官网)
- HNOI2004宠物收养所(splay维护二叉搜索树模板题)
描述 最近,阿Q开了一间宠物收养所.收养所提供两种服务:收养被主人遗弃的宠物和让新的主人领养这些宠物.每个领养者都希望领养到自己满意的宠物,阿Q根据领养者的要求通过他自己发明的一个特殊的公式,得出该领 ...