我正在尝试为由其他几个表引用的共享表创建EF Core代码优先配置。这是一个简单的示例,说明了我要做什么。
我有几个类,每个类都有一个简单的字符串值集合...我们称它们为“属性”。
public class Person
{
public int Id { get; set; }
...some other properties...
public ICollection<string> Attributes { get; set; }
}
public class Place
{
public int Id { get; set; }
...some other properties...
public ICollection<string> Attributes { get; set; }
}
public class Thing
{
public int Id { get; set; }
...some other properties...
public ICollection<string> Attributes { get; set; }
}
但是,EF Core无法独立处理字符串集合,因为字符串不被视为实体。因此我们需要将ICollection<string>
更改为ICollection<Attribute>
,其中Attribute
被定义为...
public class Attribute
{
public int ParentId { get; set; }
public string Value { get; set; }
}
ParentId
字段是对父对象中Id
字段的引用。这允许任意数量的不同父对象使用同一属性表。 (为每个父类创建一个单独的属性表似乎很愚蠢!)
在非EF Core环境中,创建数据库查询以填充父类对象的Attributes
集合很简单:
select Attributes.Value
from Attributes
inner join Person on Person.Id = Attributes.ParentId
在EF Core中,我可以创建一个配置来建立关系:
modelBuilder.Entity<Person>()
.HasMany( p => p.Attributes )
.WithOne()
.HasForeignKey( a => a.ParentId );
这将在Attributes
表中创建一个外键,并按照我们的期望定义关系。
例外...仅适用于一个父类。通过这种方式为具有Attributes
集合的每个类(一个简单的字符串集合)定义配置,在ParentId
表的同一Attributes
列上创建多个外键... 一个好主意!
EF Core中是否可以共享这样的表?如前所述,为每个包含简单字符串值集合的父类创建一个单独的表似乎很愚蠢。