简体   繁体   中英

EF Core Table Splitting - One table to multiple classes

My table has four columns and I want to split it between multiple classes.

table1
 key
 col1
 col2
 col3
 col4

Class ClassA 
  key
  col1
  col2

class ClassB
   key
   col3
   col4

modelBuilder.Entity().ToTable("table1");
modelBuilder.Entity().ToTable("table1");

Currently it give me

System.InvalidOperationException: 'Cannot use table 'table1' for entity type 'ClassB' since it is being used for entity type 'ClassA'

Is it possible in EF Core?

Thanks

You may need a relationship defined like the following based on to this MS docs :

modelBuilder.Entity<ClassA>()
    .HasOne(e => e.ClassB).WithOne(e => e.ClassA)
    .HasForeignKey<ClassB>(e => e.Key);
modelBuilder.Entity<ClassA>().ToTable("Products");
modelBuilder.Entity<ClassB>().ToTable("Products");

You can define base class for ClassA and ClassB :

abstract class ClassBase
{
    public int Key { get; set; }
}

public class ClassA : ClassBase
{
    public int Col1 { get; set; }
    public int Col2 { get; set; }
}

public class ClassB : ClassBase
{
    public int Col3 { get; set; }
    public int Col4 { get; set; }
}

Then you can define following mapping:

    modelBuilder.Entity<ClassA>().HasBaseType<ClassBase>();
    modelBuilder.Entity<ClassB>().HasBaseType<ClassBase>();

This will create table columns:

  • Key
  • Col1 (nullable)
  • Col2 (nullable)
  • Col3 (nullable)
  • Col4 (nullable)
  • Discriminator

Discriminator column is for determining the type of entity. You can control this column by HasDiscriminator methods. Instead of defining entities as above, you can use, for example:

    modelBuilder.Entity<ClassBase>().HasDiscriminator<int>("ClassType")
                .HasValue<ClassA>(1)
                .HasValue<ClassB>(2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM