Return 条有空房的记录

Return records with availability

我有一个场景,其中 Item 通过复合 table link 编辑到另一个 EntityEntityPeriod 值为 1 = 全周、2 = 周中或 3 = 周末。

我想要 return 所有可用的 Item,即没有 link 到 Entity,或者有 link到周中或周末,但不能两者兼而有之。假设是如果一个 Item 被 link 编辑为具有整周周期的 Entity 它不能被 link 编辑为另一个 Entity,或者如果 linked 到周中只能 linked 到周末等等。

我已经加入 ItemEntity 以满足完全可用的需求,但在其他不同情况下遇到了困难。

 var query = (from it in context.Items
              join ie in context.ItemEntity on new { ItemID = it.ID }
                               equals new { ItemID = ie.ItemID } into itLeft
              from itJoin in itLeft.DefaultIfEmpty()
              where itJoin == null
              select it);

在这种情况下,不应将设计视为问题。

型号:

Item
====
ItemID
ItemName

Entity
====
EntityID
Period

ItemEntity
==========
ItemEntity_ID
ItemID
EntityID

测试这个

 var query = (from it in context.Items
                     join ie in context.ItemEntity on new { ItemID = it.ID }
                                equals new { ItemID = ie.ItemID } into itLeft
                     from itJoin in itLeft.DefaultIfEmpty()
                     where itJoin != null && itJoin.ItemID == it.ItemID && ((itJoin.EntityID == 1 && (itJoin.EntityID != 2 || itJoin.EntityID != 3) || (itJoin.EntityID == 2 && itJoin.EntityID != 3) || (itJoin.EntityID == 3 && itJoin.EntityID != 2))
                     select it);

您可以在 ItemEntity 上加入,然后计算加入了多少 midweek/weekend Entity,并且只保留零或 1 个计数 Item,排除任何 Item 整周 Entitys.

var q = from it in Items
        join ie in ItemEntity on it.ItemID equals ie.ItemID into iej
        let ej = from ie in iej
                 join e in Entity on ie.EntityID equals e.EntityID
                 select e
        where ej.Count(e => e.Period == 2 || e.Period == 3) < 2 && !ej.Any(e => e.Period == 1)
        select it;