问题描述
实体框架(和RIA服务,我使用它)支持继承很好。数据库映射可以是单表或多表,在第一种情况下,数据库表包含一个包含类型指示符的指示列。显然,这个指示符不是在模型中可以看到,即使这是为了排序和分组而想要的东西。
我必须在其中引入一个额外的显式类型指示符基础课,如果这是我想要做的,或者有什么更好的方式来按照某种方式订购或分组?
我使用的是EF5。 >
是的,我可以想象你想要一个基类型列表的场景。不幸的是,在概念模型中无法获得鉴别器(指示符)。我可以想到的唯一方法就是像
db.BaseObjects.Where(b => ...)
.AsEnumerable()。选择(b => new {b.GetType()。Name,b})
之后,您可以按类型名称排序/分组。但是您不能在 AsEnumerable
之前的项目(选择
),所以限制数据大小的唯一方法是通过过滤( Where
)。
有一个技巧,将discriminator列作为可见属性类模型。您可以创建一个该表只显示真实的标识符列的值,并将其映射到标记为 DatabaseGeneratedOption.Computed
的属性。
请注意,这需要与代码优先(迁移)。而且插入和更新需要一些性能,因为EF必须从数据库中读取值。
Entity framework (and RIA Services, which I use it with) support inheritance nicely. The database mapping can be single-table or multi-table, and in the first case the database table includes a designator column containing the type designator.
Obviously this designator is not visible in the model, even though it's something one would like to have in order to order by and group over.
Do I have to introduce an additional explicit type designator in the base class if that's what I want to do or is there a nicer way to order or group by the type in some way?
I'm using EF5.
Yes, I can imagine scenarios where you'd want a list of base types. Unfortunately there is no way to get the discriminator (designator) in the conceptual model. The only way I can think of is something like
db.BaseObjects.Where(b => ...)
.AsEnumerable().Select (b => new {b.GetType().Name, b } )
After that you can sort/group by the type name. But you can't project (Select
) before the AsEnumerable
, so the only way to restrict the size of the data is by filtering (Where
).
There is a trick to get the discriminator column as a visible property in the class model. You can create a computed column in the table, that just displays the value of the real discriminator column, and map it to a property that is marked as DatabaseGeneratedOption.Computed
.
Note that this needs special attention with code-first (migrations). And it takes some performance with inserts and updates because EF must read the value from the database afterwards.
这篇关于实体框架继承:按类型排序/分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!