Difficulty Sending Selected Rows from WPF DataGrid to SQL Table

44 views Asked by At

I'm facing an issue with my WPF application where I need to send selected rows from a DataGrid to a SQL database table. Despite implementing the necessary logic, the methods responsible for handling the selection and sending the data are not being triggered. Unreachable Methods: The methods (CanSendSelectedRows and SendSelectedRowsToSQL) responsible for handling the selection and sending the data to the SQL database table are not being reached when expected. here are these methods:

//constructor
 public DataGridViewModel()
        {
            
            DataGridItems = new ObservableCollection<States>();
            SelectedItems = new ObservableCollection<States>();
            
            LoadDataFromDatabase();

            
            SendSelectedRowsToSQLCommand = new RelayCommand(SendSelectedRowsToSQL, CanSendSelectedRows);
         }

public ObservableCollection<States> SelectedItems
        {
            get => _selectedItems;
            set
            {
                _selectedItems = value;
                OnPropertyChanged(nameof(SelectedItems));

            }
        }

public ICommand SendSelectedRowsToSQLCommand { get;  set; }
private bool CanSendSelectedRows(object parameter)
        {
           //return true;
            // Ensure that SelectedItems is not null and contains at least one item
           return SelectedItems != null && SelectedItems.Any();
        }

public void SendSelectedRowsToSQL(object parameter)
        {
            using (var context = new DbProjectEntities())

            {
                foreach (var item in SelectedItems)
                {
                    context.orderedStateTbl.Add(new orderedStateTbl
                    {
                        orderStateId = item.StateID,
                        oStateName = item.StateName
                    });
                }
            }
        }

The button responsible for triggering the action is always enabled, even before any rows are selected in the DataGrid.

<Button Content="Send Selected Rows" 
                HorizontalAlignment="Center" VerticalAlignment="Bottom"
                Margin="0,0,0,20"
                Command="{Binding SendSelectedRowsToSQLCommand }"/>

and finally I set dataContext of my View in code behind as follow


            InitializeComponent();
            _viewmodel = new DataGridViewModel();
            DataContext = _viewmodel;

I apologize for my very simple question. could anyone help me what is my mistake or what should I do?

1

There are 1 answers

0
Arthur Edgarov On

It seems you're just not saving your changes to the database. Imagine you have a Select All button in your software, and a user selects 10,000 rows at a time. How those rows should be saved in your opinion? When you're calling DbContext.DbSet.Add? - No, that's not how it works, you're going to overload your DB with 10,000 queries.

Instead, Microsoft designed DbContext to follow the repository pattern, which means you're keeping all the changes in memory, until explicit save/commit invocation.

Thus, you're method should have one additional row:

public void SendSelectedRowsToSQL(object parameter)
{
    using (var context = new DbProjectEntities())
    {
        foreach (var item in SelectedItems)
        {
            context.orderedStateTbl.Add(new orderedStateTbl
            {
                orderStateId = item.StateID,
                oStateName = item.StateName
            });
        }

        context.SaveChanges(); // Here is the commit transaction call
    }
}

Furthermore, all the DB queries are I/O operations and since that - it is recommended to do the querying methods asynchronous. So I'd suggest you to redesign your method a bit:

public async void SaveAsync(object parameter)
{
    using var context = new DbProjectEntities();

    context.orderedStateTbl.AddRange(
        SelectedItems.Select(item => new orderedStateTbl
        {
            orderStateId = item.StateID,
            oStateName = item.StateName
        }));

    await context.SaveChangesAsync();
}