EF Core Table Splitting - One table to multiple classes

不想你离开。 提交于 2020-01-24 00:30:10

问题


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


回答1:


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");



回答2:


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


来源:https://stackoverflow.com/questions/47686775/ef-core-table-splitting-one-table-to-multiple-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!