2017-06-22 167 views
1

我想創建一個WPF應用程序與SQL連接到數據庫。對於我的測試應用程序,我使用NorthWind數據庫。我在MSDN上跟着這Tutorial創建DataContext類和我的應用程序的實體類。我還爲實體「客戶」創建了對象數據源。將數據源添加到MainWindow.xaml後,使用拖動&將其自動創建爲DataGrid。WPF Datacontext Sql更新,刪除,插入

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數據庫有關,而且與我測試過的所有其他數據庫也有關。

+0

我不明白這是一個'XAML'問題,如果你有調試器中的數據權利bevore提交它。也許更關注'SubmitChanges()'。 – Peter

+0

@彼得我認爲你是對的。我對WindowsForms應用程序進行了相同的測試,並且遇到了同樣的問題。 – daniel59

+0

數據庫位於何處?如果您正在使用本地數據庫,請檢查應用程序的* output *文件夾中是否有數據庫文件,即bin/Debug或bin/Release。您可能會在每個版本上覆蓋這一個。 – mm8

回答

1

如果您使用本地數據庫,則應確保應用程序的輸出文件夾中的數據庫文件(即bin/Debug或bin/Release)在每個構建版本上都不會被覆蓋。

換句話說,您需要確保您在每次運行時都寫入相同的數據庫文件。