SaveChanges() on a observablecollection Binded to MVVM datagrid

Filippo 41 Reputation points
2022-03-15T21:34:43.033+00:00

i'm using VS2017 and created a C# WPF MVVM app with MYSQL entityframework. In my view and view model of USERS(utenti) i binded and observable collection to a Datagrid. Everything works fine, and when i change a cell in a row i use SaveChanges() to save into the db the updated data. The only problem is when i add a row to my datagrid. when i save nothing happens. SaveChanges() works only if i modify an existing row, not if i add a row. Do you know why? I paste the code of my ViewModel

     namespace LegalNote.ViewModels
    {
    class UCAccountsVM : BaseViewModel
    {
        legalnoteEntities legEnt = new legalnoteEntities();
        public UCAccountsVM()
        {
                List<utenti> listaUtenti = (from recordset in legEnt.utenti
                               where recordset.id >= 0
                               orderby recordset.id
                               select recordset).ToList();


                AccountsList = new ObservableCollection<utenti>(listaUtenti);
        }

        private ObservableCollection<utenti> accountsList;
        public ObservableCollection<utenti> AccountsList
        {
            get
            {
                return accountsList;
            }
            set
            {
                accountsList = value;
                RaisePropertyChanged("AccountsList");
            }
        }

        private ICommand saveData;
        public ICommand SaveData
        {
            get
            {
                if (saveData == null)
                    saveData = new RelayCommand(o => salvaDati());
                return saveData;
            }
        }

        private void salvaDati()
        {
            legEnt.SaveChanges();

        }
    }
}
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,647 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes