2014-02-20 5 views
0

Я новичок в wpf, поэтому это кривая обучения для меня. У меня есть обязательная работа, поэтому любое обновление, которое я выполняю, без проблем.wpf привязка datarow сохраняет изменения, но не вставляет или удаляет

Проблема заключается в добавлении и удалении. Ни один из них не работает.

Вот мой код:

using System; 
using System.Linq; 
using System.Windows; 
using WebPortalSourceId.data; 

namespace WebPortalSourceId 
{ 
    public partial class MainWindow : Window 
    { 
    private Guid _corporationId; 

    private SuburbanPortalEntities entity; 
    public MainWindow() 
    { 
     InitializeComponent(); 
     entity = new SuburbanPortalEntities(); 
    } 

    private void Search_Click(object sender, RoutedEventArgs e) 
    { 
     if (CompanyCode.Text.Length != 3) 
     { 
     MessageBox.Show("Invalid Company Code. It must be 3 characters in length."); 
     return; 
     } 
     _corporationId = GetCorporationId(CompanyCode.Text.ToUpper()); 
     FillDataGrid(_corporationId); 
    } 

    public void FillDataGrid(Guid corporationId) 
    { 
     var query = from s in entity.Sources where s.CorporationId == corporationId select s; 
     if (query.Any()) 
     { 
     SourceDataGrid.ItemsSource = query.ToList(); 
     }  
     SourceDataGrid.Columns[2].Visibility = Visibility.Hidden; 
     SourceDataGrid.Columns[0].IsReadOnly = true; 
     SourceDataGrid.Columns[1].IsReadOnly = true; 

    } 

    private Guid GetCorporationId(string companycode) 
    { 
     return (from cs in entity.CorporationStructures 
      where cs.Company == companycode & 
       cs.IsActive & 
       cs.Branch == null 
      select cs.CorporationId).FirstOrDefault(); 
    } 

    private void Save_Click(object sender, RoutedEventArgs e) 
    { 
     entity.SaveChanges(); 
    } 

    private void SourceDataGrid_AddingNewItem(object sender, System.Windows.Controls.AddingNewItemEventArgs e) 
    { 
     var sources = new Source(); 
     sources.CorporationId = _corporationId; 
     sources.Description = string.Empty; 
     sources.IsActive = true; 
     sources.Name = string.Empty; 
     sources.SourceId = Guid.NewGuid(); 
     sources.TokenId = Guid.NewGuid(); 
     e.NewItem = sources; 
    } 

    } 

} 

И моя XAML:

<Window x:Class="WebPortalSourceId.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="Web Portal SourceId" Height="475" Width="948" WindowStartupLocation="CenterScreen" ResizeMode="NoResize"> 
    <Grid> 
    <TextBox Name="CompanyCode" HorizontalAlignment="Left" Height="23" Margin="337,11,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="48" MaxLength="3" TextAlignment="Center" CharacterCasing="Upper"/> 
    <Label Content="Company Code" HorizontalAlignment="Left" Margin="240,10,0,0" VerticalAlignment="Top"/> 
    <DataGrid Name="SourceDataGrid" Margin="10,43,10,10" CanUserReorderColumns="False" CanUserResizeRows="False" HorizontalContentAlignment="Stretch" FontFamily="Microsoft YaHei" AddingNewItem="SourceDataGrid_AddingNewItem" SelectionMode="Single" SelectionUnit="CellOrRowHeader"/> 
    <Button Name="Search" Content="Search" HorizontalAlignment="Left" Margin="390,11,0,0" VerticalAlignment="Top" Width="75" Height="23" Click="Search_Click"/> 
    <Button x:Name="Save" Content="Save" Margin="470,11,397,0" VerticalAlignment="Top" Height="23" Click="Save_Click" HorizontalContentAlignment="Center"/> 


    </Grid> 
</Window> 

Что мне не хватает?

ответ

0
public void FillDataGrid(Guid corporationId) 
{ 
    var query = from s in entity.Sources where s.CorporationId == corporationId select s; 
    query.Load(); 

    SourceDataGrid.ItemsSource = entity.Sources.Local; 
    SourceDataGrid.Columns[2].Visibility = Visibility.Hidden; 
    SourceDataGrid.Columns[0].IsReadOnly = true; 
    SourceDataGrid.Columns[1].IsReadOnly = true; 

} 

Queryable<T>.ToList() создает List, что Entity Framework ничего не знает о. Однако EF по-прежнему сохраняет ссылку на каждый элемент SourceProxy, который он инициировал из базы данных.

Используя DbSet<T>.Local, мы получаем ObservableCollection, с которым EF привязан к вставкам и удалению. Однако имейте в виду, что он медленный. Не говоря уже о том, что теперь доступ к нему должен выполняться через поток пользовательского интерфейса.

Таким образом, даже доступ к БД к DbSet<T> должен выполняться через поток пользовательского интерфейса. Что плохо.

Лучший способ справиться с этим - создать вас самостоятельно ObservableCollection, а также обработать Remove/Add.

Смежные вопросы