J
J
Jaguar_sea2014-09-16 09:07:34
WPF
Jaguar_sea, 2014-09-16 09:07:34

How to perform CRUD operations using Entity Framework?

I'm trying to figure out a bunch of WPF, MVVM Patern, Entity Framework.
Currently there is:
MainWindow.xaml

<Window x:Class="CashReg.Client.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" Title="Банки">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <DataGrid Grid.Row="0" 
                  ItemsSource="{Binding Banks}"
                  SelectedItem="{Binding SelectedItem}"
                  AutoGenerateColumns="False"
                  IsReadOnly="True"
                  CanUserAddRows="False" CanUserSortColumns="True">
            <DataGrid.InputBindings>
                <KeyBinding Key="Delete" Command="{Binding DeleteCommand}"/>
            </DataGrid.InputBindings>
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding city}" Header="Город"></DataGridTextColumn>
                <DataGridTextColumn Binding="{Binding Name}" Header="Название"></DataGridTextColumn>
                <DataGridTextColumn Binding="{Binding bik}" Header="БИК"></DataGridTextColumn>
                <DataGridTextColumn Binding="{Binding kor_acc}" Header="Корр. счет"></DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
        <Button Grid.Row="1" Content="Сохранить" Command="{Binding Save}" HorizontalAlignment="Left"></Button>
    </Grid>
</Window>

MainWindow.xaml.cs
using System;
using System.Windows;

namespace CashReg.Client
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private MainWindowViewModel _viewModel = new MainWindowViewModel();
        public MainWindow()
        {
            InitializeComponent();
            DataContext = _viewModel;
        }

        protected override void OnClosed(EventArgs e)
        {
            _viewModel.Dispose();
            base.OnClosed(e);
        }
    }
}

MainWindowViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Input;
using System.Collections.ObjectModel;
using CashReg.Data;
using System.Runtime.CompilerServices;

namespace CashReg.Client
{
    public class MainWindowViewModel : INotifyPropertyChanged, IDisposable
    {
        /// <summary>
        /// Наш контекст данных
        /// </summary>
        private CashRegContext _dataContext;

        public ObservableCollection<Bank> Banks { get; private set; }

        public MainWindowViewModel()
        {
            _dataContext = new CashRegContext();
            Banks = new ObservableCollection<Bank>(_dataContext.Banks);
            Save = new ActionCommand(SaveChanges) { IsExecutable = true };
        }

        private void SaveChanges()
        {
            _dataContext.SaveChanges();
        }

        public ActionCommand Save { get; set; }

        public ActionCommand DeleteCommand { get; set; }

        private Bank selectedItem;

        public Bank SelectedItem
        {
            get { return selectedItem; }
            set
            {
                if (selectedItem == value)
                    return;
                selectedItem = value;
                OnPropertyChanged("SelectedItem");
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            var handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName)); 
            }
        }

        public void Dispose()
        {
            // освобождение ресурсов контекста при удалении ViewModel
            _dataContext.Dispose();
        }
    }
}

ActionCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace CashReg.Client
{
    public class ActionCommand : ICommand
    {
        private Action _action;
        private bool _isExecutable;

        public bool IsExecutable
        {
            get { return _isExecutable; }
            set
            {
                _isExecutable = value;
                if (CanExecuteChanged == null)
                {
                    return;
                }
                CanExecuteChanged(this, new EventArgs());

            }
        }

        public ActionCommand(Action action)
        {
            _action = action;
        }

        /// <summary>
        /// Предикат показывает можно ли запускать команды при заданном аргументе.
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public bool CanExecute(object parameter)
        {
            return IsExecutable;
        }

        public event EventHandler CanExecuteChanged;

        /// <summary>
        /// Что должна выполнять команда
        /// </summary>
        /// <param name="parameter"></param>
        public void Execute(object parameter)
        {
            _action();
        }
    }
}

There is also a set of entity classes.
At the same time, I can’t understand how the operations of adding, editing, deleting should be performed. If it's not difficult, give a link to an article where you can read about it. My Google searches were unfortunately unsuccessful.
PS If someone points out errors in my code, I will be very grateful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri, 2014-09-16
@Jaguar_sea

_dataContext.Banks.Add(new Bank());

_dataContext.Banks.Remove(bank));

After these you save.
I advise you to read the literature:
Troelsen E. - The C # 2010 programming language and the .NET 4 platform - 2010, Chapter 23.
Nagel K., Ivien B., Glynn J., Watson K. C # 4.0 and the .NET4 platform for professionals - 2011, Chapter 31.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question