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
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
Q&A

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();
    }
}
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)

0 answers

Sign up to answer this question »

This community is part of the Codidact network. We have other communities too — take a look!

You can also join us in chat!

Want to advertise this community? Use our templates!

Like what we're doing? Support us! Donate