WPF Datacontext Sql更新,删除,插入

时间:2017-06-22 07:44:40

标签: c# wpf datacontext

我想创建一个带有数据库SQL连接的WPF应用程序。对于我的测试应用程序,我使用的是NorthWind数据库。我在MSDN上遵循这个Tutorial来创建DataContext类和我的Application的实体类。我还为实体" Customers"创建了对象数据源。使用Drag& amp;将数据源添加到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数据库,还适用于我测试过的所有其他数据库。

1 个答案:

答案 0 :(得分:1)

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

换句话说,您需要确保在每次运行时都写入相同的数据库文件。