c# WPF MvvM application DataGrid not updating to the database

I am working on a WPF application using MvvM Light. I have created a databinding for my DataGrid and when I edit something there it does not update to the database and I am not sure where I went wrong.

This is my View code:

<Window 
    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:NinjaApp_V2.Views"
    xmlns:ViewModel="clr-namespace:NinjaApp_V2.ViewModel" xmlns:NinjaApp_V2="clr-namespace:NinjaApp_V2" x:Name="NinjaCRUDWindow" x:Class="NinjaApp_V2.Views.NinjaCRUD"
    mc:Ignorable="d"
    Title="NinjaCRUD" Height="300" Width="300">
<Window.Resources>
    <CollectionViewSource x:Key="ninjaViewSource" d:DesignSource="{d:DesignInstance {x:Type NinjaApp_V2:ninja}, CreateList=True}"/>
</Window.Resources>
<Window.DataContext>
    <Binding Path="AddNinja" Source="{StaticResource Locator}"/>
</Window.DataContext>
<Grid DataContext="{Binding Source={StaticResource Locator}}" Margin="0,10,3.6,0.4">
    <DataGrid x:Name="DataGridNinjas" ItemsSource="{Binding Ninjas.Ninjas}">
        <DataGrid.ItemBindingGroup>
            <BindingGroup/>
        </DataGrid.ItemBindingGroup>
    </DataGrid>
    <Button Command="{Binding SaveCommand}" CommandParameter="{Binding ElementName=AddWindow}" Margin="0,180,211,0">Save</Button>
</Grid>

The .cs of that view is completly empty as I have seen in multiple examples.

AddNinjaVM contains the SaveCommand and looks like this:

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using NinjaApp_V2.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace NinjaApp_V2.ViewModel
{
    public class AddNinjaVM : ViewModelBase
    {
        public NinjaVM Ninja { get; set; }

        public ICommand SaveCommand { get; set; }

        private NinjaListVM _ninjas;

        public AddNinjaVM(NinjaListVM ninjas)
        {
            _ninjas = ninjas;
            Ninja = new NinjaVM();
            SaveCommand = new RelayCommand<NinjaCRUD>(Save);
        }

        private void Save(NinjaCRUD obj)
        {
            using (var context = new NinjaApp_DatabaseEntities())
            {
                context.SaveChanges();
            }

            _ninjas.Ninjas.Add(Ninja);
            obj.Hide();
        }
    }
}

I have followed a working example from school for this. This is a part I have been stuck on for the second day now and I just do not get why it is not working in my application. Could someone perhaps help me out?

1 answer

  • answered 2017-10-23 10:06 Prateek Shrivastava

     private void Save(NinjaCRUD obj)
            {
                using (var context = new NinjaApp_DatabaseEntities())
                {
                    **context.<DBtable>.Add(obj);**
                    context.SaveChanges(); <---- This is where it is wrong.
                }
    
                _ninjas.Ninjas.Add(Ninja);  
                obj.Hide();
            }
    

    You need to add the object to the context.Ninjas collection first and then call context.SaveChanges.

    Entity Framework Concepts

    In Entity Framework - assume DbContext (NinjaApp_DatabaseEntities in your code) to be the Database. All tables in the actual database will appear as List (Classes called Entities) in this DbContext.

    when you have to add a record to a table, you create a row which must have a value for each column in that table and then its inserted. Similarily, in entity framework, when you have to add a new record to table, you got to create an object of the Entities Type.

    From you example & comments - I visualize that the Table name is "ninjas" - Hence you see context.ninjas

    Next you want to add a record to this table "ninjas" - which means the object that you can add to it must also be of type of "ninjas" class.

    Since you have the code, you must the Actual Type of Class representing the table and you must create a new object of it - assign values and then Add it to the context.ninjas.Add() and finally call context.SaveChanges();

    Refer: http://www.entityframeworktutorial.net/EntityFramework4.3/add-entity-using-dbcontext.aspx

      //create DBContext object
            using (var dbCtx = new SchoolDBEntities())
            {
                //Add Student object into Students DBset
                dbCtx.Students.Add(newStudent);
    
                // call SaveChanges method to save student into database
                dbCtx.SaveChanges();
            }