Entity Framework Code-First(10.2):Entity Mappings

Entity Mappings using Fluent API:

Here, we will learn how to configure an entity using Fluent API.

We will use the following Student and Standard domain classes of the school application.

public class Student
{
    public Student()
    { 

    }
    public int StudentID { 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 StandardId { get; set; }
    public string StandardName { get; set; }

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

 }

Configure Default Schema:

First, let‘s configure a default schema for the tables in the database. However, you can change the schema while creating the individual tables. The following example sets the default Admin schema.

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 default schema
        modelBuilder.HasDefaultSchema("Admin");
    }
}

Map Entity to Table:

Code-First will create the database tables with the name of DbSet properties in the context class - Students and Standards in this case. You can override this convention and can give a different table name than the DbSet properties, 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)
        {
                //Configure default schema
            modelBuilder.HasDefaultSchema("Admin");

            //Map entity to table
            modelBuilder.Entity<Student>().ToTable("StudentInfo");
            modelBuilder.Entity<Standard>().ToTable("StandardInfo","dbo");

        }
    }
}

As you can see in the above example, we start with the Entity<TEntity>() method. Most of the time, you have to start with the Entity<TEntity>() method to configure it using Fluent API. We have used ToTable() method to map Student entity to StudentInfo and Standard entity to StandardInfo table. Notice that StudentInfo is in Admin schema and StandardInfo table is in dbo schema because we have specified dbo schema for StandardInfo table.

Map Entity to Multiple Table:

The following example shows how to map Student entity to multiple tables in the database.

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)
        {
            modelBuilder.Entity<Student>().Map(m =>
            {
                m.Properties(p => new { p.StudentId, p.StudentName});
                m.ToTable("StudentInfo");

            }).Map(m => {
                m.Properties(p => new { p.StudentId, p.Height, p.Weight, p.Photo, p.DateOfBirth});
                m.ToTable("StudentInfoDetail");

            });

            modelBuilder.Entity<Standard>().ToTable("StandardInfo");

        }
    }
}

As you can see in the above example, we mapped some properties of Student entity to StudentInfo table and other properties to StudentInfoDetail table using Map() method. Thus, Student entity will split into two tables, as shown below.

Map method need the delegate method as a parameter. You can pass Action delegate or lambda expression in Map method, as shown below.

using System.Data.Entity.ModelConfiguration.Configuration;

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)
        {
            modelBuilder.Entity<Student>().Map(delegate(EntityMappingConfiguration<Student> studentConfig)
            {
                studentConfig.Properties(p => new { p.StudentId, p.StudentName });
                studentConfig.ToTable("StudentInfo");
            });

            Action<EntityMappingConfiguration<Student>> studentMapping = m =>
            {
                m.Properties(p => new { p.StudentId, p.Height, p.Weight, p.Photo, p.DateOfBirth });
                m.ToTable("StudentInfoDetail");
            };
            modelBuilder.Entity<Student>().Map(studentMapping);

            modelBuilder.Entity<Standard>().ToTable("StandardInfo");

        }
    }
}
时间: 2024-08-01 10:56:20

Entity Framework Code-First(10.2):Entity Mappings的相关文章

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

SQL Server安全(10/11):行级别安全(Row-Level Security)

在保密你的服务器和数据,防备当前复杂的攻击,SQL Server有你需要的一切.但在你能有效使用这些安全功能前,你需要理解你面对的威胁和一些基本的安全概念.这篇文章提供了基础,因此你可以对SQL Server里的安全功能充分利用,不用在面对特定威胁,不能保护你数据的功能上浪费时间. 不像其它一些工业强度的数据库服务器.SQL Server对于单个数据记录,缺少内建机制,称作行级别安全(Row-Level Security).这篇文章会探寻为什么你可能想使用这样的行级别颗粒的数据访问安全和你如何能

Entity Framework Code-First(10.1):EntityTypeConfiguration

EntityTypeConfiguration Class in Code-First: Before we start to configure using Fluent API, let's see an important class of Fluent API. EntityTypeConfiguration is an important class in Fluent API. EntityTypeConfiguration provides you important method

Entity Framework Code First学习系列

Entity Framework Code First学习系列目录 Entity Framework Code First学习系列说明:开发环境为Visual Studio 2010 + Entity Framework 5.0+MS SQL Server 2012,在数据库方面Entity Framework Code First在Entity Framework 5.0仅支持MS SQL Server数据库.在接下来的随笔中,均使用项目名称为Portal的控制台应用程序为例.具体的系统学习目