yaacoub Amna yaacoub Amna - 1 month ago 8
C# Question

how can i get First and Last date from mysql table using EF in c#

this is my code to get First date and it works for me and i can show 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 Last date

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


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

Answer

Try this:

var getlastDate = 
            dc.table.Where(b => b.number == n).
            OrderByDescending(b => b.Date).
            First();