You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何筛选指定PartyId关联的FinishedGoodsItem数据?

解决LINQ关联查询直接返回目标实体的问题

现有两张关联表:

关联表(FGParty)

-----------------
partyId| ItemID |       
-----------------
 1     |    1   |
 1     |    2   |
 2     |    2   |
 2     |    3   |
 ----------------

Item表(FGItem)

-----------------
ItemID| Name    |       
-----------------
 1    | item1   |
 2    | item2   |
 3    | item3   |
 ----------------

需求是筛选出指定PartyId(示例中为1)关联的Item数据,且直接返回FinishedGoodsItem类型的实体(即代码中的i)。

原代码中错误地尝试通过new FinishedGoodsItem()构造新对象,实际上直接返回查询到的i即可,因为i本身就是FinishedGoodsItem类型的实例。

修改后的代码

var partyId = 1;
List<FinishedGoodsItem> itemList;
itemList = (from i in _unitFinishedGoods.FGItem.GetAll()
            join p in _unitFinishedGoods.FGParty.GetAll(x => x.PartyId == partyId) 
            on i.Id equals p.FGItemId
            select i).ToList();

关键说明

  1. 移除了_unitFinishedGoods.FGItem.GetAll()后的.ToList():如果使用ORM(如Entity Framework),保留IQueryable状态可以让框架将关联查询转换为SQL语句,只从数据库返回符合条件的数据,避免加载全部Item到内存后再过滤,提升性能。
  2. 直接select i:无需构造新对象,i就是关联后筛选出的目标实体,直接返回即可得到符合要求的List<FinishedGoodsItem>。
  3. 最后调用.ToList():将查询结果转换为List类型,匹配itemList的定义。

方法链写法(可选)

如果偏好方法链风格,也可以这样写:

var partyId = 1;
List<FinishedGoodsItem> itemList = _unitFinishedGoods.FGItem.GetAll()
    .Join(
        _unitFinishedGoods.FGParty.GetAll(x => x.PartyId == partyId),
        item => item.Id,
        partyItem => partyItem.FGItemId,
        (item, partyItem) => item
    )
    .ToList();

内容的提问来源于stack exchange,提问作者Toha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:22:41