efcore
efcore copied to clipboard
Support non-mapped intermediary generic base classes (with TPH/TPC)
General desired architecture:
public abstract class TPHRoot
{
public int Id {get;set;}
public abstract string Type {get;}
}
public abstract class UnmappedGeneric<TValue> : TPHRoot
{
public virtual TValue Value {get;set;}
}
public class StringValue : UnmappedGeneric<string>
{
public override string Type => "string";
public string StringValue {get{return Value;}set{Value=value;}}
}
public class IntValue : UnmappedGeneric<int?>
{
public override string Type => "int";
public int? IntValue {get{return Value;}set{Value=value;}}
}
With mappings (plz forgive, this was for EF6)
public class TPHRootMap : EntityTypeConfiguration<TPHRoot>
{
public TPHRootMap()
{
Map<StringValue>(x =>
x.Requires("Type")
.HasValue("string");
Map<IntValue>(x =>
x.Requires("int")
.HasValue("string");
Ignore(x => x.Value);
}
}
public class StringValueMap : EntityTypeConfiguration<StringValue>() { public StringValueMap() { } }
public class IntValueMap : EntityTypeConfiguration<IntValue>() { public IntValueMap() { } }
Exception message: The abstract type 'TPHRoot' has no mapped descendants and so cannot be mapped. Either remove 'TPHRoot' from the model or add one or more types deriving from 'TPHRoot' to the model.
Stack trace:
This Stackoverflow question (for EF6) highlights the issue http://stackoverflow.com/questions/5776635/
Alternatively..
In 7, am I able to map the intermediary generic as the TPH Root? ie:
modelBuilder.Entity(typeof(UnmappedGeneric<>))
.HasDiscriminator("type")
.HasValue<StringValue>("string")
.HasValue<IntValue>("int");
This should be possible, @AndriySvyryd to give guidance
@JoeBrockhaus In EF7 it's possible to do this with the following calls:
modelBuilder.Entity<TPHRoot>().HasDiscriminator<string>("Type")
.HasValue<StringValue>("string")
.HasValue<IntValue>("int");
modelBuilder.Entity<StringValue>().Ignore(e => e.Value);
modelBuilder.Entity<IntValue>().Ignore(e => e.Value);
The model will have 3 entity types: TPHRoot, StringValue and IntValue mapped to the same table