LINQ连接具有扁平化结果(SelectMany?)



我有一个项目表和项目类型表,由项目类型ID相关。我有下面的查询表达式(尽管我更喜欢链式语法,但我无法理解它(。

var items = (from i in _context.Items
join it in _context.ItemTypes on i.ItemTypeId equals it.ItemTypeId
select new { i, ItemCategory = it.ItemCategory, ItemTypeName = it.ItemTypeName }).AsQueryable();

生成的JSON看起来像这样的

data: [
{
i: {
itemId: 72,
itemTypeId: 8,
},
itemCategory: "Book",
itemTypeName: "Book"
}
]

但我更喜欢这个而不是

data: [
{
itemId: 72,
itemTypeId: 8,
itemCategory: "Book",
itemTypeName: "Book"
}
]

我知道我可以通过选择新的{field1,field2}来做到这一点,但我有很多字段,每次需要的时候我真的不想搞砸。

所以我的问题是1。我怎样才能做到这一点?和2。可以用链式方法语法代替吗?

谢谢!

如果您使用EF,并且与表之间存在关系,那么您需要执行类似于的操作

var items = _context.Items.Include(x => x.ItemType)
.Select(x => new 
{
ItemId = x.Id,
ItemTypeId = x.ItemTypeId,
ItemCategory = x.ItemCategory,
ItemTypeName = x.ItemType.Name
});

如果两个列表之间没有关系:

var result = items.Join(itemTypes,
itm => itm.ItemTypeId,
type => type.Id,
(itm, type) => new
{
ItemId = itm.Id,
ItemTypeId = itm.ItemTypeId,
ItemCategory = itm.ItemCategory,
ItemTypeName = type.ItemType.Name
});

最新更新