Code: Select all
AppDbContext.cs
Code: Select all
public class AppDbContext : DbContext
{
public DbSet People { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionString = "server=localhost;database=wpfproba;user=root;password=;";
optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
}
}
< /code>
MainWindow.cs
Code: Select all
namespace wpfproba2
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Refresh();
}
private void Refresh()
{
using (var context = new AppDbContext())
{
var students = context.People.ToList();
StudentDataGrid.ItemsSource = students;
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Window2 window2 = new Window2();
window2.Show();
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
Refresh();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (StudentDataGrid.SelectedItem is Person picked)
{
using var context = new AppDbContext();
context.People.Remove(picked);
context.SaveChanges();
Refresh();
}
}
}
}
< /code>
MainWindow.xaml.cs
Window x:Class="wpfproba2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006 ... esentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/marku ... ility/2006"
xmlns:local="clr-namespace:wpfproba2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
< /code>
Window2.cs
public partial class Window2 : Window
{
public Window2()
{
InitializeComponent();
}
private void add_Click(object sender, RoutedEventArgs e)
{
string name = Name.Text;
string location = Location.Text;
if (!string.IsNullOrWhiteSpace(name))
{
try
{
using (var db = new AppDbContext())
{
var person = new Person { Name = name, Location = location };
db.People.Add(person);
db.SaveChanges();
}
MessageBox.Show("Save successful!");
name.Clear();
location.Clear();
}
catch (Exception ex)
{
MessageBox.Show("An error occurred: " + ex.Message);
}
}
else
{
MessageBox.Show("Please enter a name.");
}
}
}
< /code>
Person.cs
namespace wpfproba2
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
}
}
< /code>
Meine Frage:>