yaacoub Amna yaacoub Amna - 1 year ago 87
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 Source

You can use OrderByDescending() + First():

var lastDate = table.Where(b => b.number == n)
     .OrderByDescending(b => b.Date)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download