问题
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