locked
how to update selected record in EF RRS feed

  • 問題

  • Hi All.

    In my DataGrid each row has button to modify according record. The method that I created try to update first record

    public static int UpdateEmployee(EmployeeDT employee)
    {
        try
        {
            int result = 0;
            using (var context = new Model1())
            {
                var emp = context.Employees.FirstOrDefault<Employee>();
    
                emp.EmployeelId = employee.EmployeeId;
                emp.Name = employee.Name;
                emp.Depatrment = employee.Department;
                emp.IsActive = employee.IsActive;
                emp.UpdatedDate = employee.UpdatedDate;
                emp.UpdatedBy = employee.UpdatedBy;
    
                context.Entry(employee).State = EntityState.Modified;
                context.SaveChanges();
             }
             return result;
        }
        catch (Exception ex)
        {
            throw new Exception("The data did not updated." + ex.ToString());
        }
    }


    I would like to modify record where was clicked Edit button. How to change code of the method to modify selected record?

    Thanks


    • 已編輯 zleug 2020年8月18日 下午 06:56
    2020年8月18日 下午 06:55

所有回覆

  • Use this

    Employee employee = dataGridName.SelectedItem as Employee;

    EDIT

    Okay this is more of an example.

    Working class, nothing fancy.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.EntityFrameworkCore;
    
    namespace NorthStockConfiguration.Classes
    {
        public class EmployeeOperations
        {
            public static List<Employees> GetEmployeeList()
            {
                using (var context = new NorthwindContext())
                {
                    return context.Employees.AsNoTracking().ToList();
                }
            }
    
            public static bool Update(Employees employee)
            {
                using (var context = new NorthwindContext())
                {
                    context.Attach(employee).State = EntityState.Modified;
                    return context.SaveChanges() == 1;
                }
            }
        }
    }


    XAML

    <Window x:Class="DataGridSimple.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:DataGridSimple"
            mc:Ignorable="d"
            Title="Entity Framework simple" Height="317.411" Width="611.161" ResizeMode="NoResize">
        <Grid Loaded="Grid_Loaded">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="347*"/>
                <ColumnDefinition Width="49*"/>
            </Grid.ColumnDefinitions>
            <DataGrid 
                x:Name="EmployeeGrid" 
                AutoGenerateColumns="False" 
                HorizontalAlignment="Left" 
                Height="204" 
                Margin="34,10,0,0" 
                VerticalAlignment="Top" 
                Width="535" 
                Grid.ColumnSpan="2">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Title" Binding="{Binding TitleOfCourtesy}" />
                    <DataGridTextColumn Header="First" Binding="{Binding FirstName}" />
                    <DataGridTextColumn Header="last" Binding="{Binding LastName}" />
                    <DataGridTextColumn Header="Birth date" Binding="{Binding BirthDate}" />
                    <DataGridTextColumn Header="Hired date" Binding="{Binding HireDate}" />
                    <DataGridTextColumn Header="Home phone" Binding="{Binding HomePhone}" />
                </DataGrid.Columns>
                
            </DataGrid>
            <Button 
                x:Name="CurrentEmployeeButton" 
                Content="Current" 
                HorizontalAlignment="Left" 
                Margin="34,239,0,0" 
                VerticalAlignment="Top"
                Width="75" 
                Click="CurrentEmployeeButton_Click"/>
        </Grid>
    </Window>

    Code behind

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using Microsoft.EntityFrameworkCore;
    using NorthStockConfiguration;
    using NorthStockConfiguration.Classes;
    using static System.Windows.WindowStartupLocation;
    
    namespace DataGridSimple
    {
    
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
    
                WindowStartupLocation = CenterScreen;
            }
    
            private void Grid_Loaded(object sender, RoutedEventArgs e)
            {
                EmployeeGrid.ItemsSource = EmployeeOperations.GetEmployeeList();
            }
    
            private void CurrentEmployeeButton_Click(object sender, RoutedEventArgs e)
            {
                var employee = EmployeeGrid.SelectedItem as Employees;
                if (!EmployeeOperations.Update(employee))
                {
                    MessageBox.Show("Update failed");
                }
            }
        }
    }

    Same works with a button on current row


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange



    • 已提議為解答 Naomi N 2020年8月18日 下午 07:26
    • 已取消提議為解答 Naomi N 2020年8月18日 下午 07:26
    • 已編輯 KareninstructorMVP 2020年8月18日 下午 08:57
    • 已提議為解答 Naomi N 2020年8月18日 下午 09:32
    2020年8月18日 下午 07:12
  • Well, the simplest solution would be to get the correct row to update first, e.g. (and, of course, don't attempt to change the ID in the code)

     var emp = context.Employees.Where(emp=>emp.EmployeeId == employee.EmployeeId).FirstOrDefault();


    Looking for new opportunities

    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles


    • 已編輯 Naomi N 2020年8月18日 下午 07:15
    • 已提議為解答 DA924x 2020年8月18日 下午 08:15
    2020年8月18日 下午 07:13
  • I've updated my reply, I did not use a button for each row but the code logic remains the same.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    2020年8月18日 下午 08:47
  • Hi zleug,

    Thank you for posting here.

    You seem to be using Entity Framework 6 instead of Entity Framework Core, so you can modify the button click event in Karen code to look like this:

            private void Button_Click(object sender, RoutedEventArgs e)
            {
                People people = dataGrid.SelectedItem as People;
                using (Model1 model = new Model1())
                {
                    model.Entry(people).State = EntityState.Modified;
    
                    model.SaveChanges();
                }
            }

    It's just a small modification, without any change in thinking.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2020年8月19日 上午 03:23
  • Hi,

    Has your issue been resolved?

    If so, please click on the "Mark as answer" option of the reply that solved your question, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2020年9月2日 上午 09:34