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; }
    }
View Code

 

配置到两张表

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);
        }
View Code

 

生成的表结构如下

添加一个水果,会生成两条插入数据,因为两个表都要插入数据,对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; }
    }
View Code

 

老师类

public class Teacher
    {
        public string TeacherId { get; set; }
        public string TeacherName { get; set; }
        public decimal Salary { get; set; }
        public Student Student { get; set; }
    }
View Code

 

配置

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);
View Code

 

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

 

 

 

转载于:https://www.cnblogs.com/jinshan-go/p/10266754.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值