База данных библиотеки
Я делаю приложение для базы данных библиотеки. Реализовал добавление, изменение и удаление объектов. Но в случае, если объект с внешним ключом, мне приходится вводить него, хотя техническая информация должна быть сокрыта для пользователя. Можно вместо него выводить какое-то еще одно поле, но тогда уникальность отпадает. Не знаю, что делать. Приложил диаграмму всех классов. MainWindow.xaml.cs:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Data;
using System.Data.SqlClient;
namespace Library
{
public partial class MainWindow : Window
{
private string connectionString;
private DataTable dataTable;
public MainWindow()
{
InitializeComponent();
connectionString = @"Data Source=LAPTOP-P14D9V4Q;Initial Catalog=Library; Integrated Security=True";
LibraryGrid.AutoGeneratingColumn += LibraryGrid_AutoGeneratingColumn;
}
private void LibraryView(object sender, SelectionChangedEventArgs e)
{
string selectedTable = ((ComboBoxItem)Tables.SelectedItem).Content.ToString(); // Получаем имя выбранной таблицы
string query = "SELECT * FROM " + selectedTable;
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connection);
dataTable = new DataTable();
dataAdapter.Fill(dataTable);
LibraryGrid.ItemsSource = dataTable.DefaultView;
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при выполнении запроса: " + ex.Message);
}
}
private void AddObject(object sender, RoutedEventArgs e)
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Set the SelectCommand property for dataAdapter
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT * FROM " + ((ComboBoxItem)Tables.SelectedItem).Content, connection);
dataAdapter.UpdateCommand = new SqlCommandBuilder(dataAdapter).GetUpdateCommand();
try
{
dataAdapter.Update(dataTable);
}
catch (Exception)
{
string messageBoxText = "Неправильно введено Id";
string caption = "Ошибка ввода"+Tables.SelectedItem.ToString();
MessageBoxButton button = MessageBoxButton.OKCancel;
MessageBoxImage icon = MessageBoxImage.Warning;
MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);
}
RefreshData();
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при выполнении запроса: " + ex.Message);
}
}
private void UpdateObject(object sender, RoutedEventArgs e)
{
DataRowView selectedRow = LibraryGrid.SelectedItem as DataRowView;
if (selectedRow != null)
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Set the SelectCommand property for dataAdapter
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT * FROM " + ((ComboBoxItem)Tables.SelectedItem).Content, connection);
dataAdapter.UpdateCommand = new SqlCommandBuilder(dataAdapter).GetUpdateCommand();
dataAdapter.Update(dataTable);
RefreshData();
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при выполнении запроса: " + ex.Message);
}
}
}
private void DeleteObject(object sender, RoutedEventArgs e)
{
DataRowView selectedRow = LibraryGrid.SelectedItem as DataRowView;
if (selectedRow != null)
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
selectedRow.Row.Delete();
// Set the SelectCommand property for dataAdapter
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT * FROM " + ((ComboBoxItem)Tables.SelectedItem).Content, connection);
dataAdapter.UpdateCommand = new SqlCommandBuilder(dataAdapter).GetUpdateCommand();
dataAdapter.Update(dataTable);
RefreshData();
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при выполнении запроса: " + ex.Message);
}
}
}
private void RefreshData()
{
string selectedTable = ((ComboBoxItem)Tables.SelectedItem).Content.ToString();
string query = "SELECT * FROM " + selectedTable;
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connection);
dataTable.Clear();
dataAdapter.Fill(dataTable);
LibraryGrid.ItemsSource = dataTable.DefaultView;
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при выполнении запроса: " + ex.Message);
}
}
private void LibraryGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
// Исключение Id
if (e.PropertyName.EndsWith("Id"))
e.Cancel = true;
}
}
}
MainWindow.xaml:
<Window x:Class="Library.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:Library"
xmlns:SqlServer="clr-namespace:System.Data.Entity.SqlServer;assembly=EntityFramework.SqlServer"
mc:Ignorable="d" Height="500" Width="800" ShowInTaskbar="False" Title="Библиотека" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ComboBox x:Name="Tables" Grid.Row="0" Margin="10" SelectionChanged="LibraryView"
Width="150" HorizontalAlignment="Left">
<ComboBoxItem Content="Libs"/>
<ComboBoxItem Content="Librarians"/>
<ComboBoxItem Content="Groups"/>
<ComboBoxItem Content="Faculties"/>
<ComboBoxItem Content="Students"/>
<ComboBoxItem Content="S_Cards"/>
<ComboBoxItem Content="Teachers"/>
<ComboBoxItem Content="T_Cards"/>
<ComboBoxItem Content="Departments"/>
<ComboBoxItem Content="Books"/>
<ComboBoxItem Content="Authors"/>
<ComboBoxItem Content="Categories"/>
<ComboBoxItem Content="Presses"/>
<ComboBoxItem Content="Themes"/>
</ComboBox>
<DataGrid x:Name="LibraryGrid" Grid.Row="1" Margin="10" AutoGenerateColumns="True"
ItemsSource="{Binding}">
<DataGrid.Resources>
<Style TargetType="DataGridColumnHeader">
<Setter Property="FontWeight" Value="SemiBold"/>
</Style>
</DataGrid.Resources>
</DataGrid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Grid.Row="2" Margin="10">
<Button x:Name="AddButton" Content="Добавить" Click="AddObject" Margin="5"/>
<Button x:Name="UpdateButton" Content="Изменить" Click="UpdateObject" Margin="5"/>
<Button x:Name="DeleteButton" Content="Удалить" Click="DeleteObject" Margin="5"/>
</StackPanel>
</Grid>
</Window>