EntityFramework.sqlServerCompact和Repository模式MVVM

时间:2016-09-04 05:01:18

标签: c# wpf entity-framework mvvm sql-server-ce

我有一个WPF应用程序,我使用过MVVM架构,数据库sql server compact 4。 首先是Entityframework.sqlserverCompact数据库,我使用了一个通用的存储库模式,如下所示:

    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;
     }

实现存储库的类

    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();
            }

SaveArticle被触发时,一切运行良好,我在列表(ListView)上看到新文章,但在数据库中没有。 我究竟做错了什么? 提前谢谢。