现在,我打算学习,怎么用Fluent API来配置领域类中的属性。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF4
{
   public class Student
    {
       public int StudentKey { get; set; }

       public string StudentName { get; set; }

       public int StuaentAge { get; set; }

       public string StudentEmail { get; set; }

       public Standard Standard { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF4
{
   public class Standard
    {
       public int StandardKey { get; set; }

       public int StandardName { get; set; }

       public ICollection<Student> Students { get; set; }

    }
}

请注意上面的代码中,Student,和Standard实体中的标注颜色的属性字段,我没有使用类名+ID或者ID的写法。而是使用了自定义的方式,这样Code-First默认约定就不知道,他们两个是主键列了,除非手动配置。

一、配置主键和复合主键【联合主键】

可以使用EntityTypeConfiguration类里面的HasKey方法。请注意,modelbuilder.Entity<TEntity>()泛型方法,返回的是EntityTypeConfiguration对象。

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF4
{
   public class DBContextClass:DbContext
    {
       public DBContextClass() : base("ConnectionStrings") { }
       public DbSet<Student> Students { get; set; }

       //public DbSet<Standard> Standards { get; set; }

       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {

           //配置主键:
           modelBuilder.Entity<Student>().HasKey(s => s.StudentKey);
           modelBuilder.Entity<Standard>().HasKey(s => s.StandardKey);

           base.OnModelCreating(modelBuilder);
       }
    }
}

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF4
{
   public class DBContextClass:DbContext
    {
       public DBContextClass() : base("ConnectionStrings")
       {
           Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DBContextClass>());
       }
       public DbSet<Student> Students { get; set; }

       //public DbSet<Standard> Standards { get; set; }

       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {

           //配置主键:
           //modelBuilder.Entity<Student>().HasKey(s => s.StudentKey);
           modelBuilder.Entity<Standard>().HasKey(s => s.StandardKey);

           //配置复合主键(联合主键)
           modelBuilder.Entity<Student>().HasKey(s => new { s.StudentKey, s.StudentName });

           base.OnModelCreating(modelBuilder);
       }
    }
}

得到的数据库是:

二、配置列名,列类型、列顺序

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF4
{
   public class DBContextClass:DbContext
    {
       public DBContextClass() : base("ConnectionStrings")
       {
           Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DBContextClass>());
       }
       public DbSet<Student> Students { get; set; }

       //public DbSet<Standard> Standards { get; set; }

       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {

           //配置主键:
           //modelBuilder.Entity<Student>().HasKey(s => s.StudentKey);
           modelBuilder.Entity<Standard>().HasKey(s => s.StandardKey);

           //配置复合主键(联合主键)
           modelBuilder.Entity<Student>().HasKey(s => new { s.StudentKey, s.StudentName });

           //配置列名,列类型,列顺序
           modelBuilder.Entity<Student>().Property(s => s.StuaentAge).HasColumnName().HasColumnType("int");

           base.OnModelCreating(modelBuilder);
       }
    }
}

生成的数据库:

modelBuilder.Entity<TEntity>().Property(expression) allows you to use different methods to configure a particular property, as shown below.

modelBuilder.Entity<TEntity>().Property(expression)这个方法,允许你配置指定的属性。

三、配置列是可空还是不可空

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF4
{
   public class DBContextClass:DbContext
    {
       public DBContextClass() : base("ConnectionStrings")
       {
           Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DBContextClass>());
       }
       public DbSet<Student> Students { get; set; }

       //public DbSet<Standard> Standards { get; set; }

       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {

           //配置主键:
           //modelBuilder.Entity<Student>().HasKey(s => s.StudentKey);
           modelBuilder.Entity<Standard>().HasKey(s => s.StandardKey);

           //配置复合主键(联合主键)
           modelBuilder.Entity<Student>().HasKey(s => new { s.StudentKey, s.StudentName });

           //配置列名,列类型,列顺序
           modelBuilder.Entity<Student>().Property(s => s.StuaentAge).HasColumnName().HasColumnType("int");

           //可空列
           modelBuilder.Entity<Standard>().Property(s => s.StandardName).IsOptional();

           base.OnModelCreating(modelBuilder);
       }
    }
}

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EF4
{
   public class DBContextClass:DbContext
    {
       public DBContextClass() : base("ConnectionStrings")
       {
           Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DBContextClass>());
       }
       public DbSet<Student> Students { get; set; }

       //public DbSet<Standard> Standards { get; set; }

       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {

           //配置主键:
           //modelBuilder.Entity<Student>().HasKey(s => s.StudentKey);
           modelBuilder.Entity<Standard>().HasKey(s => s.StandardKey);

           //配置复合主键(联合主键)
           modelBuilder.Entity<Student>().HasKey(s => new { s.StudentKey, s.StudentName });

           //配置列名,列类型,列顺序
           modelBuilder.Entity<Student>().Property(s => s.StuaentAge).HasColumnName().HasColumnType("int");

           //可空列
         //  modelBuilder.Entity<Standard>().Property(s => s.StandardName).IsOptional();

           //不可空
           modelBuilder.Entity<Standard>().Property(s => s.StandardName).IsRequired();

           base.OnModelCreating(modelBuilder);
       }
    }
}

后面本来已经,翻译好了,结果,网络不稳定,没备份,,现在直接贴英文了!!!

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

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.

8.3 使用Fluent API进行属性映射【Code-First系列】的更多相关文章

  1. 10.2.翻译系列:使用Fluent API进行属性映射【EF 6 Code-First】

    原文链接:https://www.entityframeworktutorial.net/code-first/configure-property-mappings-using-fluent-api ...

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

    现在,我们来学习怎么使用Fluent API来配置实体. 一.配置默认的数据表Schema Student实体 using System; using System.Collections.Gener ...

  3. 10.翻译系列:EF 6中的Fluent API配置【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/fluent-api-in-code-first.aspx EF 6 Code-Firs ...

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

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

  5. 17.翻译系列:将Fluent API的配置迁移到单独的类中【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/move-configurations-to-seperate-class-in-cod ...

  6. code First 三 Fluent API

    Entity Framework Fluent API用于配置域类以覆盖约定. 在实体框架6中,DbModelBuilder类充当Fluent API,我们可以使用它来配置许多不同的东西.它提供了比数 ...

  7. Entity Framework Code First属性映射约定

    Entity Framework Code First与数据表之间的映射方式有两种实现:Data Annotation和Fluent API.本文中采用创建Product类为例来说明tity Fram ...

  8. Entity Framework Code First (五)Fluent API - 配置关系

    上一篇文章我们讲解了如何用 Fluent API 来配置/映射属性和类型,本文将把重点放在其是如何配置关系的. 文中所使用代码如下 public class Student { public int ...

  9. Code First 关系 Fluent API

    通过实体框架 Code First,可以使用您自己的域类表示 EF 执行查询.更改跟踪和更新函数所依赖的模型.Code First 利用称为“约定先于配置”的编程模式.这意味着 Code First ...

随机推荐

  1. 《Linux内核设计与实现》读书笔记 第四章 进程调度

    第四章进程调度 进程调度程序可看做在可运行太进程之间分配有限的处理器时间资源的内核子系统.调度程序是多任务操作系统的基础.通过调度程序的合理调度,系统资源才能最大限度地发挥作用,多进程才会有并发执行的 ...

  2. Principles of measurement of sound intensity

    Introduction In accordance with the definition of instantaneous sound intensity as the product of th ...

  3. SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/D:/MyEclipseWorkSpace/Emps/WebRoot/WEB-INF/lib/slf4j-nop-1.5.6.

    错误的是HQL语句,注意写类名属性名无误,条件无误.

  4. 国内2大Git代码托管网站

    可以说GitHub的出现完全颠覆了以往大家对代码托管网站的认识.GitHub不但是一个代码托管网站,更是一个程序员的SNS社区.GitHub真正迷人的是它的创新能力与Geek精神,这些都是无法模仿的. ...

  5. Guava Supplier实例

    今天想讲一下Guava Suppliers的几点用法.Guava Suppliers的主要功能是创建包裹的单例对象,通过get方法可以获取对象的值.每次获取的对象都为同一个对象,但你和单例模式有所区别 ...

  6. 关于Unicode,字符集,字符编码,每个程序员都应该知道的事

    关于Unicode,字符集,字符编码,每个程序员都应该知道的事 作者:Jack47 李笑来的文章如何判断一个人是否聪明?中提到: 必要.清晰.且准确的概念,是一切思考的基石.所谓思考,很大程度上,就是 ...

  7. SQL Server 的 Statistics 簡介

    當你要清空「資料表(table)」,或倒入大量「資料(data;record)」,或公司「資料庫(database)」改用新版本要資料大搬家…等情形,不只是要重建「索引(index)」,還應要重建或更 ...

  8. Hystrix框架4--circuit

    circuit 在Hystrix调用服务时,难免会遇到异常,如对方服务不可用,在这种情况下如果仍然不停地调用就是不必要的,在Hystrix中可以配置使用circuit,当达到一定程度错误,就会自动调用 ...

  9. 过段时间逐步使用HTML5新增的web worker等内容

    想来快2017年了,2013年前的手机应该很少有人用了,以后逐渐使用HTML5新增的高级API吧. 先把web worker的内容再熟悉一下,因为微软虚拟学院的'面向有经验开发人员的 JavaScri ...

  10. 【PRINCE2是什么】PRINCE2认证之七大原则(2)

    我们先来回顾一下,PRINCE2七大原则分别是持续的业务验证,经验学习,角色与责任,按阶段管理,例外管理,关注产品,剪裁. 第二个原则:吸取经验教训. PRINCE2要求项目团队吸取以前的经验教训,在 ...