Search code examples
wpfmvvmado.net-entity-data-modeldbcontext

MVVM and DBContext - how to put it together?


I'm trying to follow the MVVM pattern, however I spent some good time on this issue, googled a lot and checked stackoverflow as well... No working example found so far.

Basically, I've a simple application and want to retrieve and write data to SQL server. Here's my code:

//Model

public class Visitor
{
    public string ID { get; set; }


    public string FirstName { get; set; }

    public string LastName { get; set; }
}

//ViewModel

public class VisitorViewModel : ViewModelBase
{
    public ObservableCollection<Visitor> _visitorDataCollection = new ObservableCollection<Visitor>();

    public ObservableCollection<Visitor> VisitorDataCollection
    {
        get { return _visitorDataCollection; }
        set { _visitorDataCollection = value; }
    }

    private string _firstName = "";
    private string _lastName = "";



    public string FirstName
    {
        get { return _firstName; }
        set
        {
            if (value != _firstName)
            {
                _firstName = value;
                OnPropertyChanged("FirstName");
            }
        }
    }

    public string LastName
    {
        get { return _lastName; }
        set
        {
            if (value != _lastName)
            {
                _lastName = value; 
                OnPropertyChanged("LastName");
            }
        }
    }

    public VisitorViewModel()
    {

    }
}

}

//VisitorContext class that represents a database context

public partial class VisitorContext : DbContext
{
    public VisitorContext()
        : base()
    {
    }

    public DbSet<VISITOR> Visitors { get; set; }

}

}

Nothing really fancy. However, I cannot put it "together". How to complete that to retrieve all visitors and add a new one?

Could someone point me to the right direction?


Solution

  • Just a simple example how make it all to life.

    Add some commands to VM:

    public ICommand Add {get; private set;}
    

    In constructor:

    public VisitorViewModel()
    {
       using(var context = new VisitorContext()) 
       {
           //fill collection with initial data from DbContext
           context.Visitors.ToList().ForEach(_visitorDataCollection.Add);
       }
       //setup add command, here I'm using MVVM Light like you 
       Add = new RelayCommand(()=> {
              using(var context = new VisitorContext()) 
              {
                 _visitorDataCollection.Add(context.Visitors.Add(new Visitor {
                     FirstName = this.FirstName,
                     LastName = this.LastName //read values from model properties
                 });
              }
           });
    }
    

    That's it, all you need to do is bind this ViewModel to appropriate View.