yaacoub Amna yaacoub Amna - 13 days ago 5
C# Question

How to get first and last date from MySQL table using EF in C#?

This is my code to get the first date. It works, and I can show the date in dateTimepicker.

private void ShowButton_Click(object sender, EventArgs e)
{
String constring = "datasource=;port=3306;username=;password=";

MySqlConnection connection = new MySqlConnection(constring);

int n = Convert.ToInt32(textBox1.Text);
testEntities dc = new testEntities();

var getfirstDate = dc.table.Where(b => b.number == n).First();

dateTimePicker1.Text =Convert.ToString (getfirstDate.date);
}


But, when I try to do the same with the last date

var getlastDate = dc.table.Where(b => b.number == n).Last();


an error message appears:


LINQ to Entities does not recognize the method 'project.table Lasttable' method, and this method cannot be translated into a store expression.

Answer

You can use OrderByDescending() + First():

var lastDate = table.Where(b => b.number == n)
     .OrderByDescending(b => b.Date)
     .First();
Comments