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.

Post History

66%
+2 −0
Q&A C# WPF datagrid not persisting inserts

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...

0 answers  ·  posted 2y ago by FrankLuke‭

#1: Initial revision by user avatar FrankLuke‭ · 2022-05-28T22:30:03Z (over 2 years ago)
C# WPF datagrid not persisting inserts
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>
</Window>

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