繁体   English   中英

select 带有实体框架的表的最后一条记录

[英]select the last record of a table with entity framework

您好,我正在销售表中保存一条记录,然后通过用户 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,即您插入的 object。 您不必检索它。 你的代码应该是这样的

 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM