Wednesday, June 12, 2024

LINQ Code and Tips

 LINQ Code and Tips


Entity Framework - Get a value of Column

pageTitle = db.Pages.Where(x => x.PageId == pageId).Select(x => x.PageTitle).SingleOrDefault();

Entity Framework - How to Get the current maximum value of a column

pageId = db.Pages.Max(x => x.PageId);

How to update a single colum value using EF 6 (.NET Framework)

private void MenuItem_Click(object sender, EventArgs e)
{
int index = PasswordsDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
if (index != -1)
{
// Color
ToolStripMenuItem item = (ToolStripMenuItem)sender;
string rowcolor = item.Text;
int passwordId = Convert.ToInt32(PasswordsDataGridView.Rows[index].Cells["PasswordId"].Value);
int rowcolorId = GetRowColorId(rowcolor);
using (PasswordManagerContext context = new PasswordManagerContext())
{
Password password = context.Passwords.Find(passwordId);
password.RowColor = rowcolorId;
context.SaveChanges();
}
ReloadPasswordsInDataGridView();
// Go back to original updated record ..
PasswordsDataGridView.Rows[index].Selected = true;
}
}