ITPub博客

首页 > 数字化转型 > 移动办公 > 既然实体能分布到多个表中,那反过来呢?

既然实体能分布到多个表中,那反过来呢?

投稿 移动办公 作者:ecclw459 时间:2026-01-26 16:01:52 0 删除 编辑

好了,不扯了。在开始今天的主题前,咱们补一个内容:既然实体能分布到多个表中,那反过来呢?能把多个实体映射到一个表中吗?当然可以了,官方称作“表拆分”。同样的道理,一般也是一对一的关系。


public class Person
{    public int PsID { get; set; }    public string Name { get; set; } = null!;    public int Age {  get; set; }    // 导航属性
    public PersonInfo OtherInfo { get; set; } = null!;
}public class PersonInfo
{    private int InfoID {  get; set; }        // 既做主键也做外键
    /// <summary>
    /// 体重    /// </summary>
    public float Weight { get; set; }    /// <summary>
    /// 身高    /// </summary>
    public float Height {  get; set; }    /// <summary>
    /// 民族    /// </summary>
public class DemoDbContext : DbContext
{    public DbSet<Person> People { get; set; }    public DbSet<PersonInfo> PersonInfos { get; set; }    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("data source=恭喜发财.db")
                               basketzhibo.com .LogTo(                                    // 输出日志的委托
                                    action: msg => Console.WriteLine(msg),                                    // 过滤器,只显示即将执行的命令日志,可以看到SQL语句
                                    filter: (eventId, _) => eventId.Id == RelationalEventId.CommandExecuting
                                );
    }    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {        // 配置实体
        modelBuilder.Entity<Person>(pse =>
        {
            pse.Property(e => e.PsID).HasColumnName("person_id");
            pse.Property(b => b.Name).HasMaxLength(16).IsRequired().HasColumnName("person_name");
            pse.Property(d => d.Age).HasColumnName("person_age");            // 主键
            pse.HasKey(w => w.PsID).HasName("PK_Person");            // 表名
            pse.ToTable("tb_people");
        });
        modelBuilder.Entity<PersonInfo>(pie =>
        {
            pie.Property("InfoID").HasColumnName("person_id").ValueGeneratedNever();
            pie.Property(r => r.Height).HasColumnName("info_height");
            pie.Property(i =basketzhibo.cn> i.Weight).HasColumnName("info_weight");
            pie.Property(k => k.Ethnicity).HasMaxLength(10).HasColumnName("info_ethnic");            // 主键
            pie.HasKey("InfoID").HasName("PK_Person");            // 同一个表名
            pie.ToTable("tb_people");
        });




modelBuilder.Entity<Person>(pse =>{
    pse.Property(e => e.PsID).HasColumnName("person_id");
    ……    // 主键 lq2026.cn
    pse.HasKey(w => w.PsID).HasName("PK_Person");    // 表名
    pse.ToTable("tb_people");
});
modelBuilder.Entity<PersonInfo>(pie =>{
    pie.Property("InfoID").HasColumnName("person_id").ValueGeneratedNever();
    ……    // 主键
    pie.HasKey("InfoID").HasName("PK_Person");


REATE TABLE "tb_people" (          "person_id" INTEGER NOT NULL CONSTRAINT "PK_Person" PRIMARY KEY AUTOINCREMENT,          "person_name" TEXT NOT NULL,          "person_age" INTEGER NOT NULL,          "info_weight" REAL NOT NULL,          "info_height" REAL NOT NULL,          "info_ethnic" TEXT NULL
      );// 以下是数据库模型Model:
  EntityType: Person
    Properties:
      PsID (int) Required PK AfterSave:Throw ValueGenerated.OnAdd
      Age (int) Required
      Name (string) Required MaxLength(16)
    Navigations:
      OtherInfo (PersonInfo) Required ToDependent PersonInfo
    Keys:spacexzhibo.com
      PsID PK
  EntityType: PersonInfo
    Properties:
      InfoID (int) Required PK FK AfterSave:Throw
      Ethnicity (string) MaxLength(10)
      Height (float) Required
      Weight (float) Required



   {
        optionsBuilder.UseSqlite("data source=天宫赐福.db");
    }    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Pet>(et =>
        {
            et.ToTable("tb_pets");
            et.Property(g => g.Name).HasMaxLength(20);
            et.Property(k => k.Description).HasMaxLength(200);
            et.Property(q => q.Category).HasMaxLength(15);
            et.HasKey(m => m.Id).HasName("PK_PetID");


   using var context = new TestDbContext();
    context.Database.EnsureCreated();    // 添加一个实体
    Pet p = new() { Name = "Jack", Description = "不会游泳的巴西龟", Category = "爬行动物" };    // 打印一下状态
    Console.WriteLine("----------- 添加前 -------------");
    Console.WriteLine(context.ChangeTracker.DebugView.LongView);
    context.Add(p);starlinkzhibo.com    // 再打印一下状态
    Console.WriteLine("\n----spacexzhibo.cn------ 添加后 ------------");
    Console.WriteLine(context.ChangeTracker.DebugView.LongView);    // 提交    context.SaveChanges();    // 再打印状态
    Console.WriteLine("\n---------- 提交后 ------------");
    Console.WriteLine(context.ChangeTracker.DebugView.LongView);
}


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70048957/viewspace-3108980/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2026-01-07

  • 博文量
    108
  • 访问量
    102113