[英]retrieve last value from table in linq Extention method and bind with DataGridView
我正在使用Windows Form App。 我想从数据库中检索最后一条记录并将其与datagridview绑定,我可以从中获取所有值
var query2 = _context.Products.Join(_context.ProductInfos, c => c.Id, a => a.ProductId, (a, c) => new
{
Id = a.Id,
ItemName = a.ItemName,
CategoryName = a.Category.CategoryName,
UnitName = a.Unit.UnitName,
UnitValue = a.UnitSize,
Quantity = a.Quantity,
CostPrice = c.PurchasePrice,
SalePrice = c.SalePrice,
EntryDate = c.EntryDate,
ExpireDate = c.ExpireDate
}).toList();
StockListGrid.DataSource = query2;
但我只想要最后插入的值,我用
var query2 = _context.Products.Join(_context.ProductInfos, c => c.Id, a => a.ProductId, (a, c) => new
{
Id = a.Id,
ItemName = a.ItemName,
CategoryName = a.Category.CategoryName,
UnitName = a.Unit.UnitName,
UnitValue = a.UnitSize,
Quantity = a.Quantity,
CostPrice = c.PurchasePrice,
SalePrice = c.SalePrice,
EntryDate = c.EntryDate,
ExpireDate = c.ExpireDate
}).ToList().LastOrDefault();
StockListGrid.DataSource = query2;
但是这次我没有任何价值。请告诉我如何获取上次插入的价值?
尝试使用OrderByDescending
var query2 = _context.Products.Join(_context.ProductInfos, c => c.Id, a => a.ProductId, (a, c) => new
{
Id = a.Id,
ItemName = a.ItemName,
CategoryName = a.Category.CategoryName,
UnitName = a.Unit.UnitName,
UnitValue = a.UnitSize,
Quantity = a.Quantity,
CostPrice = c.PurchasePrice,
SalePrice = c.SalePrice,
EntryDate = c.EntryDate,
ExpireDate = c.ExpireDate
}).OrderByDescending(x => x.Id).First();
或最大
var query2 = _context.Products.Join(_context.ProductInfos, c => c.Id, a => a.ProductId, (a, c) => new
{
Id = a.Id,
ItemName = a.ItemName,
CategoryName = a.Category.CategoryName,
UnitName = a.Unit.UnitName,
UnitValue = a.UnitSize,
Quantity = a.Quantity,
CostPrice = c.PurchasePrice,
SalePrice = c.SalePrice,
EntryDate = c.EntryDate,
ExpireDate = c.ExpireDate
}).Max(x => x.Id);
您的第一个查询的类型是List <...>,所有元素都具有相同的匿名类型Anonymous1
。 稍后查询的类型是Anonymous1
类的一个对象。 您的StockListGrid.DataSource
什么期望? 一个列表还是一个对象?
ToList
将所有元素从数据库管理系统(DBMS)传输到本地内存,然后您决定只需要最后一个元素
我看到两个问题
Id
最高的那个吗? 或者,也许是按字母顺序最后一个ItemName
那个? 这是不是一个最高SalePrice
? 不幸的是,实体框架不支持LastOrDefault。 请参阅受支持和不受支持的LINQ方法(对实体的linq)
解决这个问题的技巧是按照您最后考虑的属性以升序排序,然后采用FirstOrDefault
。 请记住,(取决于您的排序属性)可能会有多个具有相同排序值的项目,因此需要第二种排序
var result = dbContext.Products.Join(dbContext.ProductInfos, ...)
.OrderByDescending(joinResult => joinResult.SalePrice) // depending on your definition of Last
.ThenByDescending(joinResult => joinResult.Id) // in case there are two with same price
.FirstOrDefault();
这是非常有效的,因为只有一个元素从DBMS传输到本地内存。
请注意,结果只是一个元素,而不是列表。 如果您想将仅包含最后一个元素的List
分配给您的DataSource
.ThenByDescending(joinResult => joinResult.Id)
.Take(1)
.ToList();
同样,仅传输一个匿名对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.