zoukankan      html  css  js  c++  java
  • 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一样

     

  • 相关阅读:
    sbt commands
    SBT Assembly
    There is no setter for property named 可能产生的原因!
    JSP页面分页显示数据
    CentOS7配置FTP服务器增强版~(零基础学会FTP配置)
    Windows下将程序打包为安装包(最为简易的方式)
    Linux多线程编程详细解析----条件变量 pthread_cond_t
    在Linux中使用线程
    关于verilog中语句可不可综合
    32位先行进位加法器的实现
  • 原文地址:https://www.cnblogs.com/anyihen/p/12818446.html
Copyright © 2011-2022 走看看