77 lines
2.2 KiB
C#
77 lines
2.2 KiB
C#
|
using Avalonia.Controls;
|
||
|
using Avalonia.Interactivity;
|
||
|
using System.Linq;
|
||
|
using data.RemoteData.RemoteDataBase;
|
||
|
using data.RemoteData.RemoteDataBase.DAO;
|
||
|
using Microsoft.EntityFrameworkCore;
|
||
|
|
||
|
namespace Presence
|
||
|
{
|
||
|
public partial class AddOrEditUserWindow : Window
|
||
|
{
|
||
|
private readonly RemoteDatabaseContext _context;
|
||
|
private readonly UserDAO? _userToEdit;
|
||
|
|
||
|
public AddOrEditUserWindow()
|
||
|
{
|
||
|
InitializeComponent();
|
||
|
}
|
||
|
|
||
|
public AddOrEditUserWindow(RemoteDatabaseContext context, UserDAO? userToEdit = null) : this()
|
||
|
{
|
||
|
_context = context;
|
||
|
_userToEdit = userToEdit;
|
||
|
|
||
|
LoadGroups();
|
||
|
|
||
|
if (_userToEdit != null)
|
||
|
{
|
||
|
FioTextBox.Text = _userToEdit.FIO;
|
||
|
GroupComboBox.SelectedItem = _context.Groups.FirstOrDefault(g => g.Id == _userToEdit.GroupId);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private void LoadGroups()
|
||
|
{
|
||
|
GroupComboBox.ItemsSource = _context.Groups.ToList();
|
||
|
}
|
||
|
|
||
|
private void SaveButton_Click(object sender, RoutedEventArgs e)
|
||
|
{
|
||
|
var fio = FioTextBox.Text?.Trim();
|
||
|
var selectedGroup = GroupComboBox.SelectedItem as GroupDAO;
|
||
|
|
||
|
if (string.IsNullOrWhiteSpace(fio) || selectedGroup == null)
|
||
|
return;
|
||
|
|
||
|
if (_userToEdit == null)
|
||
|
{
|
||
|
// Новый пользователь
|
||
|
var newUser = new UserDAO
|
||
|
{
|
||
|
FIO = fio,
|
||
|
GroupId = selectedGroup.Id
|
||
|
};
|
||
|
_context.Users.Add(newUser);
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
// Обновляем существующего пользователя
|
||
|
_userToEdit.FIO = fio;
|
||
|
_userToEdit.GroupId = selectedGroup.Id;
|
||
|
|
||
|
if (_context.Entry(_userToEdit).State == EntityState.Detached)
|
||
|
{
|
||
|
_context.Users.Attach(_userToEdit);
|
||
|
}
|
||
|
_context.Entry(_userToEdit).State = EntityState.Modified;
|
||
|
}
|
||
|
|
||
|
_context.SaveChanges();
|
||
|
Close();
|
||
|
}
|
||
|
|
||
|
|
||
|
|
||
|
}
|
||
|
}
|