c# - 选择带有实体框架的表的最后一条记录
问题描述
您好,我正在销售表中保存一条记录,然后通过用户 ID 我试图访问我保存的最后一条记录以获取 ID 并使用该值保存在另一个表中
但我收到此错误:
System.InvalidOperationException: 'The LINQ expression 'DbSet<sale>
.Where(v => v.userId == __idU_0)
.LastOrDefault()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'
使查询访问最后一条记录的正确方法是什么?
private void button2_Click(object sender, EventArgs e)
{
using (var context = new AppDbContext())
{
sale S = new sale();
V.date = DateTime.Today.Date;
V.userId = dataU.idU;
context.Add(V);
var save = context.SaveChanges();
if( save > 0)
{
var idsale= context.sale.LastOrDefault(x => x.userId == dataU.idU)?.saleId;
MessageBox.Show(""+ idsale);
}
}
解决方案
S
实体框架会自动更新您插入的对象的 saleId 。您不必检索它。你的代码应该是这样的
context.Add(V);
context.SaveChanges();
MessageBox.Show(""+ s.saleId);
根据官方文档context.SaveChanges()
返回受影响的行数。因此,您可以保留对返回值的检查,这不会造成伤害。
context.Add(V);
var save = context.SaveChanges();
if ( save > 0)
{
MessageBox.Show(""+ s.saleId);
}
检查此链接以了解其工作原理https://www.entityframeworktutorial.net/faq/how-to-get-id-of-saved-entity-in-entity-framework.aspx
推荐阅读
- android - 使用 Mockito 的 Android MVP 演示者单元测试导致“想要但未调用”错误
- python - 在execution.exe中找不到错误mkl_intel_thread.1.dll
- python - 如何应用蛮力方法解决传教士和食人族问题?
- javascript - Firefox 在 BASE64 图像 DataURI 上窒息
- azure - 如何在 Terraform 中设置 Azure 逻辑应用的身份验证策略?
- python - 检测元素是否已经被点击 pygame
- javascript - 嘲笑笑话后恢复实现
- authentication - Soundcloud API 身份验证总是抛出“401 - 未经授权”
- reactjs - firebase.default.auth 不是函数
- javascript - 将组件的部分指定为子组件