LINQ:过滤子对象

本文关键字:对象 过滤 LINQ | 更新日期: 2023-09-27 18:06:11

当通过实体框架访问数据库时,我有三个实体可用:

  • stt_dictionary
  • stt_concept
  • stt_term

每一个实体都有一个第四个实体的集合,stt_change_log。

例如

stt_dictionary.stt_change_log = ICollection<stt_change_log>

前3个元素和stt_change_log之间的关系是

stt_change_log.element_id = (stt_dictionary | stt_concept | stt_term).id;

但是,由于stt_dictionary、stt_concept和stt_term的ID类型都是int,因此还需要以下操作:

stt_change_log.element_type_id = (7 | 8 | 9)

现在,当我像下面这样运行查询时,它返回具有指定ID的所有stt_change_log实体,这意味着如果我想要stt_change_log实体当stt_dictionary。id = 1时,我还获得属于id也= 1的stt_concept和stt_term实体的stt_change_log条目。换句话说,stt_change_log集合需要额外的过滤。

var daoDictionary = (from d in db.stt_dictionary
                         .Include("stt_change_log.stt_change_types")
                     where d.id == id
                     select d).FirstOrDefault();

我如何过滤stt_change_log实体指定一个值为element_type_id属性在stt_change_log集合的每个项目?

我还将添加我的意图是在单个查询中完成此操作。

LINQ:过滤子对象

遗憾的是。include不允许过滤。

您可以使用投影来执行过滤服务器大小,或者您可以根据需要延迟加载项目。

您也可以投票支持该功能在将来被包含。

最好的选择是对日志实体使用按层次表(TBH)继承映射。您将定义一个基本实体stt_change_log,然后为每种类型的日志派生一个实体类。stt_change_type将是鉴别符。

然后你的每个"主"实体都会引用特定于该实体的日志类型,过滤就神奇地为你完成了;)

阅读下面的教程来开始:

http://msdn.microsoft.com/en-us/data/jj618292

请注意,在您的情况下,您不需要在派生实体中添加任何附加属性。如果你先使用代码,搜索"table by hierarchy code first";这里有一个快速准备:http://blogs.msdn.com/b/wriju/archive/2011/05/17/code-first-ef-4-1-table-per-hierarchy.aspx