Code First:通过鉴别器查询。我知道,我不需要
我已经创建了 TPH 代码优先 tmodel,并在所需的鉴别器列上添加了 NotMappedAttribute。我可以将 DbSet 添加到子类的上下文中,并通过这些类型集进行查询,并且代码优先仍然是我的朋友。
但是,假设我有一个实体,它本身包含 BaseType 的集合,其中一些可能是一种类型,另一些可能是另一种类型。如何编写查询来获取键入的记录?顺便说一句,我不想在延迟加载的内存中集合上这样做。
假设有一个名为 Association 的类以及一些子类 AssocA 和 AssocB,它们都映射到 Associations 表并根据 AssocationTypeId 进行区分。 现在假设您有一个实体 - 为了论证起见,将其称为 Employee。例如
class Employee
{
public virtual Collection<Associations> MyAssociations {get;set;}
}
,现在我想查询数据库以查找具有 AssocA = ? 的员工。我不希望任何关联都等于 ?而是特定类型的关联。我无法使用 GetType,因为 LinqToEntities 无法使用它。我无法使用 AttributeTypeId,因为它在代码优先映射中使用。
我缺少什么?我所做的事情是合理的。但我无法模拟它。
I have created TPH code-first tmodel and added the NotMappedAttribute on the required discriminator column. I can add DbSets to my context for the subclasses and query by these typed sets and code-first is still my friend.
However, say I have an entity which itself contains a collection of BaseType, some of which might be one type, and some another. How do I write a query to get the typed records? I don't want to this on a lazy-loaded, in-memory collection by the way.
Assume a class called Association and some subclasses AssocA and AssocB, which all map to the Associations table and are discriminated on AssocationTypeId.
Now assume that you have an entity - call it Employee for arguments sake. So for example
class Employee
{
public virtual Collection<Associations> MyAssociations {get;set;}
}
Now I want to query the database to find employees with AssocA = ?. I don't want just any association to be equal to ? but the particular typed association. I can't use GetType because LinqToEntities can't work with that. I can't used the AttributeTypeId because its used in the code first mapping.
What am i missing? What I am doing is reasonable. But I can't model it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
OfType
运算符可能就是您正在寻找的:这只会查找至少具有一个
AssocA
类型关联的员工。OfType
operator is probably what you are looking for:This will find only employees which have at least one association of type
AssocA
.