WPF 数据上下文 Sql 更新、删除、插入

WPF Datacontext Sql Update, Delete, Insert

我想创建一个具有 SQL 数据库连接的 WPF 应用程序。对于我的测试应用程序,我使用的是 NorthWind 数据库。我按照 MSDN 上的这个 Tutorial 为我的应用程序创建了 DataContext class 和实体 classes。我还为实体 "Customers" 创建了对象数据源。使用拖放将数据源添加到 MainWindow.xaml 后,它会自动创建一个 DataGrid。

MainWindow.xaml:

<Window x:Class="WpfApplicationDataGridTest.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:WpfApplicationDataGridTest"
    mc:Ignorable="d"
    Title="MainWindow" Height="500" Width="525" Loaded="Window_Loaded">
<Window.Resources>
    <CollectionViewSource x:Key="customerViewSource" d:DesignSource="{d:DesignInstance {x:Type local:Customer}, CreateList=True}"/>
    <CollectionViewSource x:Key="customerOrderViewSource" Source="{Binding Order, Source={StaticResource customerViewSource}}"/>
</Window.Resources>
<Grid DataContext="{StaticResource customerOrderViewSource}">
    <Grid.RowDefinitions>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="5"/>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="40"/>
    </Grid.RowDefinitions>
    <GridSplitter Grid.Row="1" Background="DarkGray" Height="5" HorizontalAlignment="Stretch"/>
    <DataGrid x:Name="customerDataGrid" AutoGenerateColumns="False" EnableRowVirtualization="True" ItemsSource="{Binding Source={StaticResource customerViewSource}}" RowDetailsVisibilityMode="VisibleWhenSelected">
        <DataGrid.Columns>
            <DataGridTextColumn x:Name="addressColumn" Binding="{Binding Address}" Header="Address" Width="SizeToHeader"/>
            <DataGridCheckBoxColumn x:Name="boolColumn" Binding="{Binding Bool}" Header="Bool" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="cityColumn" Binding="{Binding City}" Header="City" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="companyNameColumn" Binding="{Binding CompanyName}" Header="Company Name" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="contactNameColumn" Binding="{Binding ContactName}" Header="Contact Name" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="contactTitleColumn" Binding="{Binding ContactTitle}" Header="Contact Title" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="countryColumn" Binding="{Binding Country}" Header="Country" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="customerIDColumn" Binding="{Binding CustomerID}" Header="Customer ID" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="faxColumn" Binding="{Binding Fax}" Header="Fax" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="phoneColumn" Binding="{Binding Phone}" Header="Phone" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="postalCodeColumn" Binding="{Binding PostalCode}" Header="Postal Code" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="regionColumn" Binding="{Binding Region}" Header="Region" Width="SizeToHeader"/>
        </DataGrid.Columns>
    </DataGrid>
    <DataGrid x:Name="orderDataGrid" AutoGenerateColumns="False" EnableRowVirtualization="True" ItemsSource="{Binding}" Grid.Row="2" RowDetailsVisibilityMode="VisibleWhenSelected">
        <DataGrid.Columns>
            <DataGridTextColumn x:Name="orderIDColumn" Binding="{Binding OrderID}" Header="Order ID" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="customerIDColumn1" Binding="{Binding CustomerID}" Header="Customer ID" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="employeeIDColumn" Binding="{Binding EmployeeID}" Header="Employee ID" Width="SizeToHeader"/>
            <DataGridTemplateColumn x:Name="orderDateColumn" Header="Order Date" Width="SizeToHeader">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <DatePicker SelectedDate="{Binding OrderDate, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn x:Name="requiredDateColumn" Header="Required Date" Width="SizeToHeader">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <DatePicker SelectedDate="{Binding RequiredDate, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn x:Name="shippedDateColumn" Header="Shipped Date" Width="SizeToHeader">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <DatePicker SelectedDate="{Binding ShippedDate, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTextColumn x:Name="shipViaColumn" Binding="{Binding ShipVia}" Header="Ship Via" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="freightColumn" Binding="{Binding Freight}" Header="Freight" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="shipNameColumn" Binding="{Binding ShipName}" Header="Ship Name" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="shipAddressColumn" Binding="{Binding ShipAddress}" Header="Ship Address" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="shipCityColumn" Binding="{Binding ShipCity}" Header="Ship City" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="shipRegionColumn" Binding="{Binding ShipRegion}" Header="Ship Region" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="shipPostalCodeColumn" Binding="{Binding ShipPostalCode}" Header="Ship Postal Code" Width="SizeToHeader"/>
            <DataGridTextColumn x:Name="shipCountryColumn" Binding="{Binding ShipCountry}" Header="Ship Country" Width="SizeToHeader"/>
        </DataGrid.Columns>
    </DataGrid>
    <Button x:Name="buttonSave" Content="Save" HorizontalAlignment="Right" Margin="0,0,10,8" Grid.Row="3" VerticalAlignment="Bottom" Width="75" Click="buttonSave_Click"/>
    <Button x:Name="buttonTest" Content="Test" HorizontalAlignment="Right" Margin="0,0,90,8" Grid.Row="3" VerticalAlignment="Bottom" Width="75" Click="buttonTest_Click"/>
</Grid>

MainWindow.xaml.cs:

public partial class MainWindow : Window
{
    private NorthWindDataContext northWindDataContext = new NorthWindDataContext();
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        CollectionViewSource customerViewSource = ((CollectionViewSource)(this.FindResource("customerViewSource")));
        customerViewSource.Source = northWindDataContext.Customers;
    }

    private void buttonSave_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            northWindDataContext.SubmitChanges();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

数据显示正常,但如果我尝试更新、删除或插入记录,则更改不会提交到数据库,如果我在调试期间检查值,则值会更新、删除或插入,但是如果我重新启动应用程序,更改将不会被保存。 该行为不仅适用于 NorthWind 数据库,而且适用于我测试过的所有其他数据库。

如果您使用的是本地数据库,则应确保应用程序输出文件夹中的数据库文件,即 bin/Debug 或 bin/Release 不会在每次构建时被覆盖。

换句话说,您需要确保在每个 运行.

上写入相同的数据库文件