Reputation: 95
hello I am saving a record in the sale table and then by means of the user id I am trying to access the last record that I save to get the id and use that value to save in another table
but i get this error:
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.'
What is the correct way to make the query to access the last record?
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);
}
}
Upvotes: 0
Views: 311
Reputation: 1143
Entity Framework updates the saleId of S
, the object that you inserted, automatically. You don't have to retrieve it. Your code should be like this
context.Add(V);
context.SaveChanges();
MessageBox.Show(""+ s.saleId);
The context.SaveChanges()
returns the number of rows being affected according to the official documentation. So, you can keep the check of the value returned, that would not hurt.
context.Add(V);
var save = context.SaveChanges();
if ( save > 0)
{
MessageBox.Show(""+ s.saleId);
}
Check this link to see how it works https://www.entityframeworktutorial.net/faq/how-to-get-id-of-saved-entity-in-entity-framework.aspx
Upvotes: 2