• EF6学习笔记六:实体拆分(Entity Spliting)实现TPT、表拆分(Table Spliting)实现TPH


     要专业系统地学习EF前往《你必须掌握的Entity Framework 6.x与Core 2.0》这本书的作者(汪鹏,Jeffcky)的博客:https://www.cnblogs.com/CreateMyself/

     EF的优点之一在于我们得实体模型不用匹配存储模型

    Entity Spliting

    实体拆分就是将一个实体进行配置后,映射后会在数据库中生成多张表

    来个类,里面包含图书和水果的属性

    复制代码
    public class Model1
        {
            public string Model1Id { get; set; }
            public string FruitName { get; set; }
            public decimal FruitPrice { get; set; }
            public string BookName { get; set; }
            public decimal BookPrice { get; set; }
            public DateTime AddTime { get; set; }
        }
    复制代码

    配置到两张表

    复制代码
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Model1>().Map(m =>
                {
                    m.Properties(p => new
                    {
                        p.Model1Id,
                        p.BookName,
                        p.BookPrice,
                        p.AddTime
                    });
                    m.ToTable("tb_Books");
                }).Map(m =>
                {
                    m.Properties(p => new
                    {
                        p.FruitName,
                        p.FruitPrice
                    });
                    m.ToTable("tb_Fruits");
                });
                base.OnModelCreating(modelBuilder);
            }
    复制代码

    生成的表结构如下

    添加一个水果,会生成两条插入数据,因为两个表都要插入数据,对Model进行查询的时候会进行连表查询

    这个还是有一点局限,因为只有一个model,查询的时候不能针对Fruit和Book进行查询

    Table Spliting

    多个实体映射为一张表

    学生类Student

    复制代码
    public class Student
        {
            public string StudentId { get; set; }
            public string StuName { get; set; }
            public string Number { get; set; }
            public virtual Teacher Teacher { get; set; }
        }
    复制代码

    老师类

    复制代码
    public class Teacher
        {
            public string TeacherId { get; set; }
            public string TeacherName { get; set; }
            public decimal Salary { get; set; }
            public Student Student { get; set; }
        }
    复制代码

    配置

    modelBuilder.Entity<Student>().ToTable("tb_People").HasKey(x => x.StudentId)
                    .HasRequired(x =>x.Teacher).WithRequiredPrincipal(x =>x.Student);
                modelBuilder.Entity<Teacher>().ToTable("tb_People").HasKey(x => x.TeacherId);

    生成表结构如下,和TPH一样

     

  • 相关阅读:
    c++ primer plus 第六章 课后题答案
    动态创建easyui控件的渲染问题
    晨报
    动态构建easyUI grid
    早起
    周末
    js ajax方式拼接参数
    5个月
    锻炼
    东湖夜色
  • 原文地址:https://www.cnblogs.com/anyihen/p/12818446.html
Copyright © 2020-2023  润新知