我有一个项目表和项目类型表,按项目类型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"
}
]
我知道我可以通过选择new{field1,field2}来实现,但是我有大量的字段,我真的不想每次需要的时候都去乱搞。
所以我的问题是1。我怎样才能完成这件事呢?和2。可以用链式方法语法代替吗?
谢啦!
如果您正在使用EF并且to表之间存在关系,那么您需要像这样坐:
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
});