我正在开发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();
同样,只传输一个匿名对象