这是我用来获取具有特定ID的商品和每个商品的商品详细信息的查询
public class ItemModel
{
public int ItemSeq{get;set}
public string ItemName{get;set;}
public double? Amount{get;set;}
}
public class SampleModel
{
public string Id{ get; set; }
public string Code{ get; set; }
public List<ItemModel> Items{ get; set; }
}
public List<SampleModel> GetItems(string id)
{
var items= _context.ItemTable.Where(t => t.Id== id).ToList<SampleModel>();
return list;
}
为明确要求,有两个表ItemTable
和ItemDetailTable
,而Id
是ItemTable
中的ItamDetailTable
主键和外键,而{{ 1}}对于单个ItemDetailTable
可能具有多个值,并且上面的查询从ID
返回项目和具有特定ID的详细信息,我想要的是具有按值排序的项目详细信息值ItemDetailTable
。有什么办法吗?
样本数据
ItemTable
Amount
ItemDetailTable
Id Code
1 Code1
2 Code3
我想要的是Id ItemSeq ItemName Amount
1 1 ABC1 200
1 2 ABC2 129
1 3 ABC3 549
2 1 DEF1 265
2 2 DEf2 970
的值为1时返回的值
Id
答案 0 :(得分:2)
您需要通过将ItemModel
参数传递给id
方法来返回GetItems
的排序列表。
public List<ItemModel> GetItems(string id)
{
var items = _context.SampleTable.Where(t => t.Id == id).SelectMany(x => x.Items).Where(p => p.Amount != null).OrderBy(x => x.Amount).ToList();
return items.ToList();
}
编辑:
上面的查询从ItemDetailTable返回具有特定ID的项目和详细信息
您还需要将外键属性添加到ItemDetailTable中,如
public class ItemDetailTable
{
public int ItemSeq { get; set; }
public string ItemName { get; set; }
public double? Amount { get; set; }
public string Id { get; set; } //Foreign key of ItemTable
}
public ItemTable GetItems(string id)
{
//Get "ItemTable" record from database
var item = _context.ItemTable.Where(x => x.Id == id).SingleOrDefault();
//Retrieve its "Items" and sort by ascending order
var itemDetails = item.Items.Where(x => x.Id == id).Where(p => p.Amount != null).OrderBy(x => x.Amount).ToList();
//Preare a new "ItemTable" object to return
ItemTable itemTable = new ItemTable
{
Code = item.Code,
Id = item.Id,
Items = itemDetails
};
//Return new "itemTable" with sorted list of "ItemDetailTable"
return itemTable;
}
编辑2:
public ItemTable GetItems(string id)
{
var result = (from i in _context.ItemTable
where i.Id == id
let sorting = i.Items.Where(x => x.Id == id).Where(x => x.Amount != null).OrderBy(x => x.Amount).ToList()
select new ItemTable
{
Id = i.Id,
Code = i.Code,
Items = sorting
}).FirstOrDefault(); //Or => SingleOrDefault
return result;
}