我有一些继承自基本模型的模型:
public class Filter
{
public int Id { get; set; }
public int FeedId { get; set; }
public FilterOperator FilterOperator { get; set; }
[Required, MaxLength(100)] public string Name { get; set; }
[Required, MaxLength(100)] public string Expression { get; set; }
[Required, MaxLength(100)] public string FieldName { get; set; }
}
然后我有另一个模型:
public class Conversion : Filter
{
public MathOperator MathOperator { get; set; }
public double Value { get; set; }
}
这些都与名为 Feed 的实体具有类似的关系:
public class Feed
{
public int Id { get; set; }
[Required, MaxLength(100)] public string CategoryId { get; set; }
[Required, MaxLength(2083)] public string Url { get; set; }
public FeedType Type { get; set; }
public bool Active { get; set; }
public Category Category { get; set; }
public ICollection<Conversion> Conversions { get; set; }
public ICollection<FieldMap> FieldMaps { get; set; }
public ICollection<Filter> Filters { get; set; }
public ICollection<Rule> Rules { get; set; }
public ICollection<Transformation> Transformations { get; set; }
}
当我尝试运行 add-migration
命令时,出现此错误:
Both relationships between 'Conversion' and 'Feed.Conversions' and between 'Filter' and 'Feed.Filters' could use {'FeedId'} as the foreign key. To resolve this configure the foreign key properties explicitly on at least one of the relationships.
所以在我的DbContext中我添加了这些行:
modelBuilder.Entity<Feed>().HasMany(m => m.Conversions).WithOne().HasForeignKey(m => m.FeedId);
modelBuilder.Entity<Feed>().HasMany(m => m.Filters).WithOne().HasForeignKey(m => m.FeedId);
modelBuilder.Entity<Feed>().HasMany(m => m.Rules).WithOne().HasForeignKey(m => m.FeedId);
modelBuilder.Entity<Feed>().HasMany(m => m.Transformations).WithOne().HasForeignKey(m => m.FeedId);
但我仍然遇到同样的问题。 有谁知道我可以做些什么来解决这个问题?
最佳答案
您需要移动 public ICollection<Conversion> Conversions { get; set; }
以避免错误。
自从您使用 TPH它将使用单个表来存储层次结构中所有类型的数据。鉴别器列用于识别每行代表哪种类型。
然后您可以使用以下方法获取派生实体:
public class SampleContext : DbContext
{
public DbSet<Filter> Contracts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Conversion>().HasBaseType<Filter>();
}
}
Controller :
var conversions = _context.Filters.OfType<Conversion>().ToList();
引用https://www.learnentityframeworkcore.com/inheritance/table-per-hierarchy#convention
关于entity-framework - .net core Entity Framework 两种关系可以使用相同的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57492671/