WPF MVVM - create model from database

Feb 4, 2011 at 1:18 PM

I would like to heard what is suitabale solution for this situation.

I use in WPF app Caliburn.Micro framework. I need have acess to SQL Compact DB. On DB access I use LINQ TO SQL.

For example In view I have comboBox control or listBox control. I need load items of these controls from DB.

So I create simple class on access to the DB.

[Export(typeof(IDbManager))]
public partial class DbManager : IDbManager
{

    public IList<Spirit_Users> LoadSpiritUsers()
    {
        var result = from u in _dc.Spirit_Users orderby u.Nick select u;
        return result.ToList();
    }
}

I inject this class with MEF to view model class. On use method from class on DB access in my view model class on load items to comboBox.

[Export(typeof(ILogOnViewModel))]
public class LogOnViewModel : Screen, ILogOnViewModel,
    IPartImportsSatisfiedNotification
{
    [Import]
    internal IDbManager DbManager { get; set; }

    //this property is bind on listbox or comboBox
    public BindableCollection<Spirit_Users> SpiritUsers
    {
        get { return _spiritUsers; }
        set
        {
            _spiritUsers = value;
            NotifyOfPropertyChange(() => SpiritUsers);
        }
    }


    private void ConfigureSpiritUsers()
    {
        //load items from comboBox or listBox
        var users = SettingsDbManager.LoadSpiritUsers();

        //add to the collection which is binded on control in view
        if (users.Count > 0)
        {
            foreach (var user in users)
            {
                SpiritUsers.Add(user);
            }
        }
    }


    protected override void OnActivate()
    {
        ConfigureSpiritUsers();
        base.OnActivate();
    }
}

I don’t know if my solution is correct and the most suitable in scenarion WPF app with MVVVM.

Also I need create CRUD operation from view model class to the DB. For example save some object/data to the database.

Thank for advice.