Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Comments on C# WPF datagrid not persisting inserts

Post

C# WPF datagrid not persisting inserts

+2
−0

I am working with VS 2022 and trying to make a WPF MVVM application. The application updates the items displayed in the datagrid, persisting the changes to the database upon save. However, adding a new record to the grid does not insert (without extra steps). I imagine I am missing something simple.

It seems to me as if since the updates persist from the ObservableCollection to the context without extra coding then the inserts would also.

View:

<Window x:Class="PictureWar.View.TagTagTypeWindow"
    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:PictureWar.View"
    mc:Ignorable="d"
    Title="Tags and TagTypes" Height="450" Width="800">
<Window.Resources>
    <CollectionViewSource x:Key="tagTypeViewSource" Source="{Binding TagTypes}"/>
    <CollectionViewSource x:Key="tagTagTypesViewSource" 
                          Source="{Binding Tags, Source={StaticResource tagTypeViewSource}}"/>
</Window.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <DataGrid Grid.Row="0" Grid.Column="0" x:Name="tagTypesDataGrid" AutoGenerateColumns="False" 
      EnableRowVirtualization="True" 
      ItemsSource="{Binding Source={StaticResource tagTypeViewSource}}" 
      Margin="0,0,0,0" RowDetailsVisibilityMode="VisibleWhenSelected">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding ID}"
                                Header="Tag Type Id" 
                                Width="SizeToHeader"
                                IsReadOnly="True"/>
            <DataGridTextColumn Binding="{Binding Name}" 
                                Header="Name" 
                                Width="*"/>
        </DataGrid.Columns>
    </DataGrid>
    
    <DataGrid Grid.Row="0" Grid.Column="1" x:Name="tagsDataGrid" AutoGenerateColumns="False" 
      EnableRowVirtualization="True" 
      ItemsSource="{Binding Source={StaticResource tagTagTypesViewSource}}" 
      Margin="0,0,0,0" RowDetailsVisibilityMode="VisibleWhenSelected" 
      RenderTransformOrigin="0.488,0.251">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding ID}" 
                                Header="Tag Id" 
                                Width="SizeToHeader" 
                                IsReadOnly="True"/>
            <DataGridTextColumn Binding="{Binding TagTypeID}" 
                                Header="Tag Type Id" 
                                Width="SizeToHeader"
                                IsReadOnly="False"/>
            <DataGridTextColumn Binding="{Binding Name}" Header="Name" Width="*"/>
        </DataGrid.Columns>
    </DataGrid>
    
    <Button Grid.Row="2" Grid.ColumnSpan="2" Command="{Binding SaveCommand}">Save</Button>
</Grid>

Code Behind

public partial class TagTagTypeWindow : Window
{
    public TagTagTypeWindow()
    {
        InitializeComponent();
        DataContext = new TagTagTypeViewModel();
    }
}

View Model

namespace PictureWar.ViewModel;

public class TagTagTypeViewModel : ObservableObject
{
    private ObservableCollection<TagType> _tagTypes;
    private readonly TagTypeRepository _repository;

    public TagTagTypeViewModel()
    {
        _repository = new TagTypeRepository();
        _tagTypes = new ObservableCollection<TagType>(_repository.GetAllTagTypes().ToList());
        SaveCommand = new RelayCommand(DoSave);
    }

    public IRelayCommand SaveCommand { get; }

    public ObservableCollection<TagType> TagTypes
    {
        get => _tagTypes;
        set { SetProperty(ref _tagTypes, value); }
    }

    public void DoSave()
    {
        var newTagTypes = TagTypes.Where(tt => tt.ID < 1); //extra step
        _repository.SaveAllTagTypes(newTagTypes);
    }
}

Repository

public class TagTypeRepository
{
    private readonly WarContext _context;

    public TagTypeRepository()
    {
        _context = new WarContext();
    }

    public IEnumerable<TagType> GetAllTagTypes()
    {
        return _context.TagType.Include(tt => tt.Tags);
    }

    public void SaveAllTagTypes(IEnumerable<TagType> newTagTypes)
    {
        _context.TagType.AddRange(newTagTypes); //part of the extra step
        _context.SaveChanges();
    }
}
History
Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

1 comment thread

The list used to construct the ObservableCollection is not updated (3 comments)
The list used to construct the ObservableCollection is not updated
Alexei‭ wrote almost 2 years ago

What does _context.TagType contain when you are trying to save in SaveAllTagTypes? I assume it contains the initially loaded items, because the documentation specifies that the constructor will copy all the references. That means that any change performed in the ObservableCollection will not reflect in the list used for its construction.

FrankLuke‭ wrote almost 2 years ago

_context.TagType contains the original items with any edits to them but not any inserts to the list. (I have not coded for deletion yet.)

Alexei‭ wrote almost 2 years ago

FrankLuke‭n OK. This makes sense. I haven't worked with WPF / MVVM pattern for quite some time, so the following might not apply.

Normally, the UI (the grid in this case) should not directly work with database models as what you store is typically different from what you display and also due to a separation of concerns.

The solution is to have a mapping between the view models and the database models. As a consequence, a "merge" is required (add the missing models, update the existing ones, remove the ones removed from the UI).

You have already covered the "add" part in your code. An improvement would be to have a generic function to automatically add all new TViewModels into a DbSet<TEnt>. This can be improved to get a mapping function (TViewModel -> TEnt) and support deletion.