I have a Person class, there are four tables in the database (Person, department, category, education). since I have tables linked by a foreign key, I want to store only the ID of another table in my main table, for this I have a combobox (you can select the required section and save the ID of the selected section in the database). I have three combobox controllers that display the ID and Name of each of the three tables. How can I store data in this form?
namespace PersonMVVM
{
public class PersonModel
{
public int PersonID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int PersonAge { get; set; }
public string PersonAddress { get; set; }
public string PersonContact { get; set; }
public string PersonDepartmentID { get; set; }
public string PersonLevelEductationID { get; set; }
public string PersonCategoryID { get; set; }
}
}
The main table Person is connected to other tables through foreign keys.
ViewModel looks like this
namespace PersonMVVM
{
class PersonViewModel: ViewModelBase
{
public ObservableCollection<PersonModel> PersonItems { get; }
private PersonModel _selectedPersonItem;
//Commands
public ICommand Add { get; }
public ICommand Save { get; }
public ICommand Delete { get; }
public ICommand ShowWinCommand { get; set; }
public PersonModel SelectedPersonItem
{
get => _selectedPersonItem;
set { _selectedPersonItem = value; OnpropertyChanged(nameof(this.SelectedPersonItem)); }
}
private readonly DataRepository dataRepository;
public PersonViewModel()
{
this.ShowWinCommand = new ShowWindowCommand(ShowWindow, CanShowWindow);
this.PersonItems = new ObservableCollection<PersonModel>();
this.dataRepository = new DataRepository();
getPersons();
}
public void getPersons()
{
IEnumerable<PersonModel> personModels = this.dataRepository.GetPersonModels();
foreach (PersonModel personModel in personModels)
{
this.PersonItems.Add(personModel);
}
}
private bool CanShowWindow(object obj)
{
return true;
}
private void ShowWindow(object obj)
{
var detVM = new DetailsVM(SelectedPersonItem);
var dets = new CRUDWindow(detVM);
dets.ShowDialog();
}
}
}
DataRepository
namespace PersonMVVM
{
class DataRepository
{
public IEnumerable<PersonModel> GetPersonModels()
{
var persons = new List<PersonModel>();
var departments = new List<DepartmentModel>();
var Connect = ConfigurationManager.ConnectionStrings["MysqlConnection"].ConnectionString;
using (var conn = new MySqlConnection(Connect))
using (var command = new MySqlCommand())
{
conn.Open();
command.Connection = conn;
command.CommandText = @"SELECT person.id, person.name, person.surname, person.address, person.age, person.contact, department.name AS 'department', eductation.lavel, category.name AS 'category' FROM person LEFT JOIN department ON department.id = person.departmentID LEFT JOIN eductation ON eductation.id = person.eductationLavelID LEFT JOIN category ON category.id = person.categoryID";
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
persons.Add(new PersonModel()
{
PersonID = (int)reader["id"],
Name = (string)reader["name"],
Surname = (string)reader["surname"],
PersonAddress = (string)reader["address"],
PersonAge = (int)reader["age"],
PersonContact = (string)reader["contact"],
PersonDepartmentID = (string) reader["department"],
PersonLevelEductationID = (string)reader["lavel"],
PersonCategoryID = (string)reader["category"]
}) ;
}
}
return persons;
}
public void Add(PersonModel personModel)
{
try
{
var Connect = ConfigurationManager.ConnectionStrings["MysqlConnection"].ConnectionString;
using (var conn = new MySqlConnection(Connect))
using (var command = new MySqlCommand())
{
conn.Open();
command.Connection = conn;
command.CommandText = @"insert into person(name, surname, address, age, contact, departmentID, categoryID, eductationLavelID)Values(@name, @surname, @address, @age, @contact, @departmentID, @categoryID, @eductationLavelID)";
command.Parameters.AddWithValue("@name", personModel.Name);
command.Parameters.AddWithValue("@surname", personModel.Surname);
command.Parameters.AddWithValue("@address", personModel.PersonAddress);
command.Parameters.AddWithValue("@age", personModel.PersonAge);
command.Parameters.AddWithValue("@contact", personModel.PersonContact);
command.Parameters.AddWithValue("@departmentID", personModel.PersonDepartmentID);
command.Parameters.AddWithValue("@categoryID", personModel.PersonCategoryID);
command.Parameters.AddWithValue("@eductationLavelID", personModel.PersonLevelEductationID);
command.ExecuteNonQuery();
}
}
catch (MySqlException ex)
{
Debug.WriteLine(ex.Message);
}
}
}
}
So, now when I select a specific person and click on the change button, a new window opens where I want to change or add and remove a person.
class ShowWindowCommand : ICommand
{
public event EventHandler CanExecuteChanged;
private Action<object> _Execute { get; set; }
private Predicate<object> _CanExecute { get; set; }
public ShowWindowCommand(Action<object> ExecuteMethod, Predicate<object> CanExecuteMethod)
{
_Execute = ExecuteMethod;
_CanExecute = CanExecuteMethod;
}
public bool CanExecute(object parameter)
{
return _CanExecute(parameter);
}
public void Execute(object parameter)
{
_Execute(parameter);
}
}
and SaveCommand
namespace PersonMVVM
{
class SaveCommand : ICommand
{
public event EventHandler CanExecuteChanged;
private readonly DetailsVM detailsVM;
private readonly DataRepository _dataRepository;
public SaveCommand(DetailsVM details)
{
this.detailsVM = details;
this._dataRepository = new DataRepository();
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_dataRepository.Add(detailsVM.SelectedPerson);
}
}
}
Using viewModel, I transfer the selected object to a new window.
namespace PersonMVVM
{
public class DetailsVM
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnpropertyChanged([CallerMemberName] string propName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
public PersonModel Detail { get; set; }
public ObservableCollection<DepartmentModel> DepartmentItems { get; }
private readonly DepartmentRepository departmentRepository;
private PersonModel _selectedPersonItem;
public ICommand Save { get; }
public ICommand Edit { get; }
public ICommand Delete { get; }
public DetailsVM(PersonModel detail)
{
Detail = detail;
this.DepartmentItems = new ObservableCollection<DepartmentModel>();
this.Save = new SaveCommand(this);
this.departmentRepository = new DepartmentRepository();
showDeparmentCombobox();
}
public void showDeparmentCombobox()
{
IEnumerable<DepartmentModel> departmentModels = this.departmentRepository.GetDepartmentItems();
foreach (DepartmentModel departmentModel in departmentModels)
{
this.DepartmentItems.Add(departmentModel);
}
}
public PersonModel SelectedPersonItem
{
get => _selectedPersonItem;
set { _selectedPersonItem = value; OnpropertyChanged(nameof(this.SelectedPersonItem)); }
}
}
}
MainViewModel
namespace PersonMVVM
{
class MainViewModel : INotifyPropertyChanged
{
public PersonViewModel PersonViewModel { get; } = new PersonViewModel();
public DetailsVM detailsVM { get; }
private readonly PersonModel personModel;
public NavigationViewModel NavigationViewModel { get; } = new NavigationViewModel();
public event PropertyChangedEventHandler PropertyChanged;
public MainViewModel()
{
PersonViewModel = new PersonViewModel();
detailsVM = new DetailsVM(personModel);
}
public void Initialize()
{ // this.PersonViewModel.Initialize();
}
}
}
and Xaml code. CRUDWindow.xaml.cs
namespace PersonMVVM
{
public partial class CRUDWindow : Window
{
private DetailsVM _details;
public CRUDWindow(DetailsVM details)
{
_details = details;
this.DataContext = this._details;
InitializeComponent();
}
}
}
MainWindow.xaml.cs
namespace PersonMVVM
{
public partial class MainWindow : Window
{
private readonly MainViewModel MainViewModel;
public MainWindow()
{
this.MainViewModel = new MainViewModel();
this.DataContext = this.MainViewModel;
this.Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
this.MainViewModel.Initialize();
}
}
}
This is what my application looks like:
I tried binding each of the related tables with a separate model class, but it seems to me that this is wrong.
3