【译】第24节---Fluent API - 属性映射

原文:http://www.entityframeworktutorial.net/code-first/configure-property-mappings-using-fluent-api.aspx

本节,我们将学习如何使用Fluent API配置实体类的属性。 我们将使用我们学校app的Student和Standard域类:

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; }
}

配置主键和复合主键

上面的域类,没有按照主键的Code-First约定,因为它们没有Id或{Class Name} + Id属性。

因此,你可以使用Fluent API使用EntityTypeConfiguration的HasKey()方法配置key属性,如下所示。 记住modelBuilder.Entity <TEntity>()返回EntityTypeConfiguration对象。

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 });
    }
}

配置列名、列类型和排序

默认Code-First约定为名属性创建一个同名的列名、顺序和数据类型的列。 你可以覆盖此约定,如下所示:

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(3)
                    .HasColumnType("datetime2");
    }
}

如上例所示,我们使用Property()方法为实体的属性配置任何东西。

在这里,我们使用HasColumnName来更改DateOfBirth属性的列名。 此外,我们调用HasColumnOrder和HasColumnType来更改列的顺序和数据类型。

modelBuilder.Entity <TEntity>().Property(expression)允许您使用不同的方法配置特定属性,如下所示:

为属性配置Null或Not Null列

Code-First将为原始数据类型属性创建NotNull列,因为原始数据类型不能为空,除非使用?符号或Nullable <T>。

使用IsOptional方法为属性创建一个可空的列。

以同样的方式,使用IsRequired方法创建一个NotNull列。

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();
        }
    }
}

配置列大小

Code-First将设置列的数据类型的最大大小。 您可以覆盖此约定,如下所示:

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(50);

            //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(50).IsFixedLength();

            //Set size decimal(2,2)
                modelBuilder.Entity<Student>()
                    .Property(p => p.Height)
                    .HasPrecision(2, 2);
        }
    }
}

如上例所示,我们使用HasMaxLength方法设置列的大小。

IsFixedLength方法将nvarchar转换为nchar类型。

以同样的方式,HasPrecision方法改变了十进制列的精度。

配置并发列

你可以使用ConcurrencyToken方法将属性配置为并发列,如下所示:

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();
        }
    }
}

如上例所示,我们将StudentName列设置为并发列,以便它被包含在update和delete命令的where子句中。

您也可以使用IsRowVersion()方法来将byte []属性作为并发列。

时间: 2024-08-03 00:52:28

【译】第24节---Fluent API - 属性映射的相关文章

使用Fluent API 配置/映射属性和类型

Code First约定-Fluent API配置 使用Fluent API 配置/映射属性和类型 简介 通常通过重写派生DbContext 上的OnModelCreating 方法来访问Code First Fluent API.以下示例旨在显示如何使用 Fluent API 执行各种任务,您可以将代码复制出来并进行自定义,使之适用于您的模型. 属性映射 使用Fluent API 配置/映射属性和类型 简介 通常通过重写派生DbContext 上的OnModelCreating 方法来访问Co

使用 Fluent API 配置/映射属性和类型2

1.将多个实体类映射到数据库中的一个表 要将多个实体映射到一个数据库表需要满足: a. 两个实体必须是一对一关系 b.两个实体共享一个主键 1 public class MyContext:DbContext 2 { 3 public MyContext() 4 : base("test") 5 { } 6 protected override void OnModelCreating(DbModelBuilder modelBuilder) 7 { 8 modelBuilder.En

Code First约定-Fluent API配置

转自:http://blog.163.com/m13864039250_1/blog/static/2138652482015283397609/ 用Fluent API 配置/映射属性和类型 简介 通常通过重写派生DbContext 上的OnModelCreating 方法来访问Code First Fluent API.以下示例旨在显示如何使用 Fluent API 执行各种任务,您可以将代码复制出来并进行自定义,使之适用于您的模型. 属性映射 Property 方法用于为每个属于实体或复杂

1.Relationship in Entity Framework Using Code First Approach With Fluent API【使用EF Code-First方式和Fluent API来探讨EF中的关系】

In this article, you will learn about relationships in Entity Framework using the Code First Approach with Fluent API. 在这篇文章中,你将会学习到使用EF Code-First方式和Fluent API来探讨EF中的关系(一对一,一对多,多对多). Introduction[介绍] A relationship, in the context of databases, is a

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

小分享:我有几张阿里云优惠券,用券购买或者升级阿里云相应产品最多可以优惠五折!领券地址:https://promotion.aliyun.com/ntms/act/ambassador/sharetouser.html?userCode=ohmepe03 上篇博文说过当我们定义的类不能遵循约定(Conventions)的时候,Code First 提供了两种方式来配置你的类:DataAnnotations 和 Fluent API, 本文将关注 Fluent API.  一般来说我们访问 Flu

一步一步学EF系列【2、Fluent API的方式来处理实体与数据表之间的映射关系。】

EF里面的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面,还有一个就是Fluent API,通过新增相应的配置类来覆盖默认配置另外.我们主要学习Fluent API,Data Annotations可以自行去学习一下. 补充一下为什么要用Fluent API 使用DataAnnotation非常简单,但对于EntityFramework中的特性,就要在实体类中引入Ent

使用Fluent API进行实体映射【Code-First系列】

现在,我们来学习怎么使用Fluent API来配置实体. 一.配置默认的数据表Schema Student实体 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EF4 { public class Student { public int StudentID { get; set; } publ

Entity Framework 一次加载许多个 Fluent API 映射

可通过多种方法来指定模型的 Fluent 映射(从类到数据库). 1.直接在 DbContext 类的 OnModel­Creating 方法中进行映射,如下所示: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<XsreAdminData>().Property(p => p.LoginTime).HasPrecision(18, 0); modelBu

Fluent API in Code-First【Code-First系列】

在前面的章节中,我们已经看到了各种不同的数据注解特性.现在我们来学习一下Fluent API. Fluent API是另外一种配置领域类的方式,它提供了更多的配置相比数据注解特性. Mappings[映射] To Database[转成数据库] Model-wide Mapping[模型映射] Set default Schema[设置默认的Schema] Set Custom Convetions[自定义约定] Entity Mapping[实体映射] To Single or Multipl