Code First:通过鉴别器查询。我知道,我不需要

发布于 2024-12-28 16:56:18 字数 647 浏览 1 评论 0原文

我已经创建了 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

四叶草在未来唯美盛开 2025-01-04 16:56:18

OfType 运算符可能就是您正在寻找的:

var query = from e in context.Employees
            where e.MyAssociations.OfType<AssocA>().Any()
            select e;

这只会查找至少具有一个 AssocA 类型关联的员工。

OfType operator is probably what you are looking for:

var query = from e in context.Employees
            where e.MyAssociations.OfType<AssocA>().Any()
            select e;

This will find only employees which have at least one association of type AssocA.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文