Entity Framework Code-First(16):Move Configurations

Move Configurations to Separate Class in Code-First:

By now, we have configured all the domain classes in OnModelCreating method in the previous sections. When you have a large number of domain classes, then configuring every class in OnModelCreating can become unmanageable. Code-First enables you to move all the configurations related to one domain class to a separate class.

In the below example, we configured Student entity.

public class SchoolDBContext: DbContext
{
    public SchoolDBContext(): base()
    {
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
    public DbSet<StudentAddress> StudentAddress { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
            modelBuilder.Entity<Student>().ToTable("StudentInfo");

            modelBuilder.Entity<Student>().HasKey<int>(s => s.StudentKey);

            modelBuilder.Entity<Student>()
                    .Property(p => p.DateOfBirth)
                    .HasColumnName("DoB")
                    .HasColumnOrder(3)
                    .HasColumnType("datetime2");

            modelBuilder.Entity<Student>()
                    .Property(p => p.StudentName)
                    .HasMaxLength(50);

                modelBuilder.Entity<Student>()
                    .Property(p => p.StudentName)
                    .IsConcurrencyToken();

            modelBuilder.Entity<Student>()
                .HasMany<Course>(s => s.Courses)
                .WithMany(c => c.Students)
                .Map(cs =>
                        {
                            cs.MapLeftKey("StudentId");
                            cs.MapRightKey("CourseId");
                            cs.ToTable("StudentCourse");
                        });
    }
}

Now, you can move all the configurations related to Student entity to a separate class which derives from EntityTypeConfiguration<TEntity>. Consider the following StudentEntityConfigurations class.

public class StudentEntityConfiguration: EntityTypeConfiguration<Student>
{
    public StudentEntityConfiguration()
    {

            this.ToTable("StudentInfo");

            this.HasKey<int>(s => s.StudentKey);

            this.Property(p => p.DateOfBirth)
                    .HasColumnName("DoB")
                    .HasColumnOrder(3)
                    .HasColumnType("datetime2");

            this.Property(p => p.StudentName)
                    .HasMaxLength(50);

            this.Property(p => p.StudentName)
                    .IsConcurrencyToken();

            this.HasMany<Course>(s => s.Courses)
                .WithMany(c => c.Students)
                .Map(cs =>
                        {
                            cs.MapLeftKey("StudentId");
                            cs.MapRightKey("CourseId");
                            cs.ToTable("StudentCourse");
                        });
    }
}

As you can see above, we have moved all the configuration for the Student entity into constructor of StudentEntityConfiguration, which is derived from EntityTypeConfiguration<Student>. You need to specify entity type in a generic place holder for which you include configurations, Student in this case.

Now, you can inform Fluent API about this class, as shown below.

public class SchoolDBContext: DbContext
{
    public SchoolDBContext(): base()
    {
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
    public DbSet<StudentAddress> StudentAddress { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
            // Moved all Student related configuration to StudentEntityConfiguration class
            modelBuilder.Configurations.Add(new StudentEntityConfiguration());

    }
}

Thus, you can use a separate class to configure a domain class to increase the readability and maintainability.

时间: 2024-10-26 06:59:15

Entity Framework Code-First(16):Move Configurations的相关文章

Entity Framework Code First (三)Data Annotations

Entity Framework Code First 利用一种被称为约定(Conventions)优于配置(Configuration)的编程模式允许你使用自己的 domain classes 来表示 EF 所依赖的模型去执行查询.更改追踪.以及更新功能,这意味着你的 domain classes 必须遵循 EF 所使用的约定.然而,如果你的 domain classes 不能遵循 EF 所使用的约定,此时你就需要有能力去增加一些配置使得你的 classes 能够满足 EF 所需要的信息. C

Entity Framework Code First (二)Custom Conventions

------------------------------------------------------------------------------------------------------------ 注意:以下所讨论的功能或 API 等只针对 Entity Framework 6 ,如果你使用早期版本,可能部分或全部功能不起作用! --------------------------------------------------------------------------

Entity Framework Code First (一)Conventions

Entity Framework 简言之就是一个ORM(Object-Relational Mapper)框架. Code First 使得你能够通过C#的类来描述一个模型,模型如何被发现/检测就是通过一些约定(Conventions).Conventions 就是一系列规则的集合,被用于对基于类别定义的概念模型的自动装配. 这些约定都被定义于 System.Data.Entity.ModelConfiguration.Conventions 命名空间下. 当然你可以进一步地对你的模型作出配置,

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

Entity Framework Code First (八)迁移 Migrations

参考页面: http://www.yuanjiaocheng.net/entity/Persistence-in-EF.html http://www.yuanjiaocheng.net/entity/crud-in-connected.html http://www.yuanjiaocheng.net/entity/crud-in-Disconnected.html http://www.yuanjiaocheng.net/entity/add-entity-in-disconnected.h

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

上一篇文章我们讲解了如何用 Fluent API 来配置/映射属性和类型,本文将把重点放在其是如何配置关系的. 文中所使用代码如下 public class Student { public int ID { get; set; } public string Name { get; set; } public DateTime EnrollmentDate { get; set; } // Navigation properties public virtual Address Address

Entity Framework Tutorial Basics(2):What is Entity Framework?

What is Entity Framework? Writing and managing ADO.Net code for data access is a tedious and monotonous job. Microsoft has provided an O/RM framework called "Entity Framework" to automate database related activities for your application. Microso

Entity Framework Tutorial Basics(1):Introduction

以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/entity-framework5-introduction.aspx ----------------------------------------------------------------------------------------------------------------------

Entity Framework Tutorial Basics(37):Lazy Loading

Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means delaying the loading of related data, until you specifically request for it. For example, Student class contains StudentAddress as a complex property