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.

Datagrid in MVVM saves edits but not inserts

+1
−0

I am writing a todolist application in WPF with MVVM. I display the goals in a datagrid and the editing works fine. Changes made in the grid are saved to the DB when I click save. However, adding a new record does not persist during a save. Each goal may have subtasks associated with it that are handled in a detail row. Perhaps stranger, edits and additions to the subtasks persist.

When debugging, I found that the additions to the grid make it to the ObsdrvableCollection, but they are not in the _context.Goals. Edits on existing records can be seen in both the ObservableCollection and in the _context.Goals.

What do I need to change to get the additions into the _context?

I am using the Microsoft.Toolkit.Mvvm library.

public class GoalsViewModel : ObservableObject
...
_goals = new ObservableCollection<Goal>(_repository.GetAllGoals().ToList());
...
public ObservableCollection<Goal> Goals
{
    get => _goals;
    set { SetProperty(ref _goals, value); }
}
...
public void SaveAll()
{
    _repository.SaveChanges();
}

The repository SaveChanges() is merely _context.SaveChanges();

This is the view.

<Window x:Class="TodoList.View.GoalsWindow"
   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:TodoList.View"
    mc:Ignorable="d"
    Title="Goals" Height="450" Width="800">
<Window.Resources>
    <CollectionViewSource x:Key="goalsViewSource" Source="{Binding Goals}" />
    <CollectionViewSource x:Key="difficultyLevels" Source="{Binding DifficultyLevels}"/>
</Window.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <DataGrid Grid.Column="0"
              x:Name="goalsDataGrid"
              AutoGenerateColumns="False" 
              EnableRowVirtualization="True" 
              IsReadOnly="False"
              ScrollViewer.CanContentScroll="True" 
              ScrollViewer.VerticalScrollBarVisibility="Auto"
              ItemsSource="{Binding Source={StaticResource goalsViewSource}}" 
              Margin="0,0,0,0" 
              RowDetailsVisibilityMode="VisibleWhenSelected">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding ID}"
                        		Header="Id" 
								Width="SizeToCells"
                                ElementStyle="{StaticResource NumericCell}"
                        		IsReadOnly="True" />
            <DataGridTemplateColumn Width="Auto">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="Done!"
                                Command="{Binding DataContext.MarkDoneCommand,
                                    RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
                                CommandParameter="{Binding}"
                                Margin="5" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTextColumn Binding="{Binding Name}"
                        		Header="Name" 
								Width="75"
                        		IsReadOnly="False" />
            <DataGridTextColumn Binding="{Binding Description}"
                        		Header="Description" 
								Width="150"
                                ElementStyle="{StaticResource WrappingText}"
                        		IsReadOnly="False" />
            <DataGridComboBoxColumn DisplayMemberPath="Name"
                                    SelectedValuePath="ID"
                                    ItemsSource="{Binding Source={StaticResource difficultyLevels}}"
                                    SelectedValueBinding="{Binding Path=DifficultyLevelID}"
                                    Header="Difficulty"
                                    Width="SizeToCells" />
            <DataGridTextColumn Binding="{Binding GoalItems.Count}" 
                                Header="#Items" 
						        Width="SizeToHeader"
                                ElementStyle="{StaticResource NumericCell}"
                                IsReadOnly="True" />
            <DataGridTextColumn Binding="{Binding DateCreated, StringFormat='MM-dd-yyyy'}" 
                                Header="Date Created" 
						        Width="SizeToHeader"
                                IsReadOnly="True" />
            <DataGridTextColumn Binding="{Binding DateCompleted, StringFormat='MM-dd-yyyy'}" 
                                Header="Date Completed" 
						        Width="SizeToHeader"
                                IsReadOnly="True" />
        </DataGrid.Columns>
        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <DataGrid ItemsSource="{Binding GoalItems}" AutoGenerateColumns="False">
                    <DataGrid.Columns>
                        <DataGridCheckBoxColumn Binding="{Binding IsCompleted}"/>
                        <DataGridTextColumn Binding="{Binding Description}"/>
                    </DataGrid.Columns>
                </DataGrid>
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>
    </DataGrid>

    <Button Grid.Row="1" 
            Grid.Column="0" 
            Command="{Binding SaveAllCommand}" 
            Content="Save All Goals" />
</Grid>
History
Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

1 answer

+1
−0

Entity Framework is able to save the changes by using a tracking mechanism (i.e. what is added, deleted, removed).

I guess _repository.GetAllGoals() implementation is something like _context.Goals or _context.Set<Goal>(), so when you are constructing the ObservableCollection you actually get a list of EF models references. Any update (change in property value or any change in the child properties) of a list item is a change in the EF model and SaveChanges will know about it through the tracking mechanism.

However, when adding or removing items from your ObservableCollection, these changes will be done outside of the EF tracking mechanism. EF can track such changes only when done via the DbSet:

  • _context.Goals.Add(...) or _context.Set<Goal>.Add(...)
  • _context.Goals.Remove(...) or _context.Set<Goal>.Remove(...)

One way to do this is to identify added or removed items before SaveChanges and explicitly add them to the set. Something along the lines:

// I assume that goal has some kind of auto-generated Id. If this is not the case (e.g. working with GUIDs), another mechanism should be used to identify the brand-new goals
var toAdd = _goals.Where(g => g.Id == 0);
_context.Goals.AddRange(toAdd);
_context.SaveChanges();

Note: when working on larger applications, there is a clear separation between the UI and the data fetch/persistence. This can be done by avoiding working directly with EF models in the UI, but instead working with view models which are very similar to EF models, but include only the required properties (maybe not everything should be visible) and may define new properties.

The fetch and persistence flow would be like the following:

  • fetch - get goals list (EF models) -> map them to a list of goal view models -> ObservableCollection is built based on that list
  • persistence - the VM list is merged into the DbSet (i.e. add what's missing, update existing entities, remove what is extra).
History
Why does this post require moderator attention?
You might want to add some details to your flag.

1 comment thread

Thank you for the explanation. It seems odd that EF does not track additions but can detect edits. (2 comments)

Sign up to answer this question »