Search code examples
c#wpfentity-frameworkmvvmsql-server-ce

EntityFramework.sqlServerCompact and Repository pattern MVVM


I have a WPF application, I have used MVVM architecture, database sql server compact 4. Entityframework.sqlserverCompact database first, and I used a generic repository pattern as follows:

    public interface IRepository: IDisposable 
     {
          IQueryable<T> All<T>() where T : class;
          void InsertAsync<T>(T entity) where T: class ;
          Task<T> GetByIdAsync<T>(int id) where T: class ;
          Task EditAsync<T>(T entity) where T : class;
          Task DeleteAsync<T>(T entity) where T : class;
     }

The class that implement the Repository

    public class TryitRepository : IRepository
       {       
         private readonly MyEntityContext context;
         public TryitRepository()
           {
              this.context = new MyEntityContext();
           }
         public IQueryable<T> All<T>() where T : class
           {
              return this.context.Set<T>();
           }
         public void Dispose()
           {
             if (this.context != null) this.context.Dispose();
           }        
         public void InsertAsync<T>(T entity) where T : class
           {
             this.context.Set<T>().Add(entity);
             this.context.SaveChanges();
           }
        }

// ViewModel

    public class ArticleViewModel : ObjectBase
        {
          public readonly IRepository article;

          public ArticleViewModel()
             {            
                article =  new TryitRepository();
                this.LoadData();
             }

          private void LoadCommand()
            {
               this.EditCommand = new CustomCommand(this.EditArticle, this.CanEditArticle);
               this.SaveCommand= new CustomCommand(this.SaveArticle, this.CanSaveArticle);
              this.DeleteCommand = new CustomCommand(this.DeleteArticle, this.CanDeleteArticle);          
            }

          private bool CanSaveArticle(object obj)
            {
              return true;
            }
          private void SaveArticle(object obj)
            {          
              Article artikel = new Article() { Name = "newarticle", Color = "Pink", Price = 125.95, Articlenr = 15547878, Items_In_Package= 12 };
              article.InsertAsync<Article>(artikel);

              this.LoadData();
            }

When the SaveArticle is fired, everything runs well, I see the new article on the list (ListView) but not in the database. what am I doing wrong? Thanks in advance.


Solution

  • Solved!

    see answer of ErikEJ in the link below:

    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/e7f7a713-b0fd-4716-a19d-4421e8be4c88/forcing-db-changes-to-commit-in-sql-ce-?forum=sqlce