如何实现Icommand添加新客户?

时间:2015-06-21 17:22:53

标签: c# wpf entity-framework mvvm ef-code-first

我是MVVM模式的新手,我正在尝试实现一个向数据库添加新客户的代码。 我的XAML文件中有2个按钮和2个文本框,一个按钮用于更新,另一个用于添加带有文本框文本的新客户。但是当我点击按钮"添加"没有任何反应,客户未添加到我的数据库中。我正在使用EntityFramework和CodeFirst。 这是我的代码:

型号:

public class Customer
{
    [Key]
    public int CustomerId { get; set; }

    public string FullName { get; set; }

    public string Phone { get; set; }
}

视图模型:

public class CustomerViewModel : ViewModelBase
{
    private List<Customer> _customers;
    private Customer _currentCustomer;
    private CustomerRepository _repository;

    public CustomerViewModel()
    {
        _repository = new CustomerRepository();
        _customers = _repository.GeCustomers();
        WireCommands();
    }

    private void WireCommands()
    {
        UpdateCustomerCommand = new RelayCommand(UpdateCustomer);
    }

    public RelayCommand UpdateCustomerCommand { get; private set; }
    public RelayCommand AddCustomerCommand { get; private set; }

    public List<Customer> Customers
    {
        get { return _customers; }
        set { _customers = value; }
    }

    public Customer CurrentCustomer
    {
        get { return _currentCustomer; }
        set
        {
            if (_currentCustomer != value)
            {
                _currentCustomer = value;
                OnPropertyChanged("CurrentCustomer");
                UpdateCustomerCommand.IsEnabled = true;
            }
        }
    }

    public void UpdateCustomer()
    {
        _repository.UpdateCustomer(CurrentCustomer);
    }

    public void AddCustomer(Customer customer)
    {
        _repository.NewCustomer(customer);

    }

存储库:

public List<Customer> GeCustomers()
    {
        return _customers;
    }

    public void UpdateCustomer(Customer SelectedCustomer)
    {
        Customer customerToChange = _customers.Single(c => c.CustomerId == SelectedCustomer.CustomerId);
        customerToChange = SelectedCustomer;
    }

    public void NewCustomer(Customer customer)
    {
        _context.Customers.Add(customer);
        _context.SaveChanges();

    }

但是,当我点击按钮时没有任何反应,并且客户未添加到数据库中。

0 个答案:

没有答案