Building Entity Framework Generic Repository 2 Connected

A few weeks ago, we looked a first article about Disconnected Repository. In this article let’s complete it with another piece off the puzzle, the connected Generic Repository.

A few weeks ago, we looked at the first part, i.e., Disconnected Repository. In this article, let’s complete that with another piece of the puzzle, the connected Generic Repository. In this new Repository type, a very important new actor appears, that is none other than ObservableCollection<T>. This is an inseparable friend for Connected Generic Repository.

Index

  • Entity Framework Generic Repositories Connected
  • Set<TEntity> DbContext method
  • Example Classes
  • Building Entity Framework Generic Repositories Connected
    • All / AllAsync
    • Find / FindAsync
    • GetData / GetDataAsync
    • SaveChanges / SaveChangesAsync
    • HasChanges / HasChangesAsync
  • Extracting the Interface
  • WPF Example
  • Extending ConGeneriRepository<TEntitiy>
  • Test Project

Entity Framework Generic Repositories Connected

Entity Framework generic repository connected is used in state process as WPF, Silverlight, Windows Forms, console app, etc.

This repository works with group changes, and it has fixed to ItemsControls. This generic repository type works with direct DataGrid modifications.

Its main characteristics are,

  • Should receive the DbContext from dependency injection.
  • Should implement an IDisposable interface for releasing unmanaged resources.
  • Should have a DbContext protected property. This property will be alive during generic repository life and will only die in the Dispose method.
  • The DbContext property will hear all repository changes.
  • It doesn’t have methods (add, remove and update) because these actions are performed through the Local DbSet property. Local is ObservableCollection<TEntity> (INotifyCollectionChanged) and it usually will be linked directly to (ListBox, ListView, DataGrid, etc).
  • The repository connected has a SaveChanged method to send all changes to DataBase.
  • It has a SaveChanged method.
    Entity Framework Generic Repository

We must consider Connected Repository use because it has much impact on connection database consumption. This process consumes a connection for each user and screen loaded.

The ObservableCollection<T> is the key for the Repository, it as the intermediary between user/machine interactions and DbSet/DbContext. The ObservableCollection<T> receive the data from the database through queries and listen to the insert/delete changes through your event CollectionChanged and the modified by the event INotifiedPropertyChanged of the model.

Set<TEntity> DbContext method

Set<TEntity> the same as in the Disconnected Repository is very important, but in this case, our Connected Repository save its reference in a protected field because it has to be available in all repository live.

For more info, you read the DbSet<T> section y Disconnected Repository.

Example Classes

This is the example class.

  1. public partial class MyDBEntities : DbContext  
  2. {  
  3.     public MyDBEntities()  
  4.         : base("name=MyDBEntities")  
  5.     {  
  6.     }  
  7.    
  8.     public virtual DbSet<City> Cities { get; set; }  
  9.     public virtual DbSet<FootballClub> FootballClubs { get; set; }  
  10.    
  11.     protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  12.     {  
  13.         modelBuilder.Entity<City>()  
  14.             .Property(e => e.Name)  
  15.             .IsUnicode(false);  
  16.    
  17.         modelBuilder.Entity<FootballClub>()  
  18.             .Property(e => e.Name)  
  19.             .IsUnicode(false);  
  20.    
  21.         modelBuilder.Entity<FootballClub>()  
  22.             .Property(e => e.Members)  
  23.             .HasPrecision(18, 0);  
  24.     }  
  25. }  
  26.   
  27. public partial class City  
  28. {  
  29.     public int Id { get; set; }  
  30.    
  31.     [Required]  
  32.     [StringLength(50)]  
  33.     public string Name { get; set; }  
  34.    
  35.     [Column(TypeName = "numeric")]  
  36.     public decimal? People { get; set; }  
  37.    
  38.     [Column(TypeName = "numeric")]  
  39.     public decimal? Surface { get; set; }  
  40.    
  41.     public ICollection<FootballClub> FootballClubs { get; set; }  
  42. }  
  43.   
  44. public partial class FootballClub  
  45. {  
  46.     public int Id { get; set; }  
  47.    
  48.     public int CityId { get; set; }  
  49.    
  50.     [Required]  
  51.     [StringLength(50)]  
  52.     public string Name { get; set; }  
  53.    
  54.     [Column(TypeName = "numeric")]  
  55.     public decimal Members { get; set; }  
  56.    
  57.     [Required]  
  58.     [StringLength(50)]  
  59.     public string Stadium { get; set; }  
  60.    
  61.     [Column(TypeName = "date")]  
  62.     public DateTime? FundationDate { get; set; }  
  63.    
  64.     public string Logo { get; set; }  
  65. }  

Building Entity Framework Generic Repositories Disconnected

In the first step, we will create the generic ConGenericRepository class.

  1. public class ConGenericRepository < TEntity > : IDisposable where TEntity: class {  
  2.     protected internal readonly DbContext _dbContext;  
  3.     protected internal readonly DbSet < TEntity > _dbSet;  
  4.     public ConGenericRepository(DbContext dbContext) {  
  5.         if (dbContext == nullthrow new ArgumentNullException(nameof(dbContext), $ "The parameter dbContext can not be null");  
  6.         _dbContext = dbContext;  
  7.         _dbSet = _dbContext.Set < TEntity > ();  
  8.     }  
  9.     public void Dispose() {  
  10.         if (_dbContext != null) _dbContext.Dispose();  
  11.     }  
  12. }  

To start, we will inject the DbContext object, will consult the DbSet and will save in a dbset field.

The class should implement the IDisposible interface for releasing the unmanaged resources. The class has a generic constraint from reference types.

Some methods are very similar that Disconnected in the description but are different in implementation.

Let’s go build all methods.

All / AllAsync

The All/AllAsync methods returns the all table data.

  1. public ObservableCollection < TEntity > All() {  
  2.     _dbSet.Load();  
  3.     var result = _dbSet.Local;  
  4.     return result;  
  5. }  
  6. public Task < ObservableCollection < TEntity >> AllAsync() {  
  7.     return Task.Run(() => {  
  8.         return All();  
  9.     });  
  10. }  

In use,

  1. [TestMethod]  
  2. public void All_OK()  
  3. {  
  4.     ObservableCollection<FootballClub> result = instance.All();  
  5.   
  6.     Assert.IsNotNull(result);  
  7.     Assert.IsTrue(result.Count > 0);  
  8. }  

The method All/Async load the complete table in the Local (ObservableCollection) property and return the collection. The local property continuous listen the changes.

Find / FindAsync

The Find/FindAsync methods, is very similar to All/AllAsync methods, but Find/FindAsync search a simple row for PK. The PK can be simple or complex. It returns one row always.

  1. public TEntity Find(params object[] pks) {  
  2.     if (pks == nullthrow new ArgumentNullException(nameof(pks), $ "The parameter pks can not be null");  
  3.     var result = _dbSet.Find(pks);  
  4.     return result;  
  5. }  
  6. public Task < TEntity > FindAsync(object[] pks) {  
  7.     return Task.Run(() => {  
  8.         return Find(pks);  
  9.     });  
  10. }  

The param pks behavior is identical to Disconnected, view this section of Disconnected article for more info.

In use,

  1. [TestMethod]  
  2. public void Find_OK() {  
  3.     object[] pks = new object[] {  
  4.         1  
  5.     };  
  6.     FootballClub result = instance.Find(pks);  
  7.     Assert.AreEqual(result.Id, 1);  
  8. }  

GetData / GetDataAsync

Like Find/FindAsync, the methods GetData/GetDataAsync are very similar than All/AllAsync unlike, GetData has an Expression<Func<TEntity,bool>> parameter for filter the query and the Find/FindAsync return only one item and GetData/GetDataAsync returns a collection although the collection has one item.

  1. public ObservableCollection < TEntity > GetData(Expression < Func < TEntity, bool >> filter) {  
  2.     if (filter == nullthrow new ArgumentNullException(nameof(filter), $ "The parameter filter can not be null");  
  3.     _dbSet.Where(filter).Load();  
  4.     var filterFunc = filter.Compile();  
  5.     var result = new ObservableCollection < TEntity > (_dbSet.Local.Where(filterFunc));  
  6.     RelinkObservableCollection(result);  
  7.     return result;  
  8. }  
  9. public Task < ObservableCollection < TEntity >> GetDataAsync(Expression < Func < TEntity, bool >> filter) {  
  10.     return Task.Run(() => {  
  11.         return GetData(filter);  
  12.     });  
  13. }  

Note we have used a private method RelinkObservableCollection,

  1. private void RelinkObservableCollection(ObservableCollection<TEntity> result)  
  2. {  
  3.     result.CollectionChanged += (sender, e) =>  
  4.     {  
  5.         switch (e.Action)  
  6.         {  
  7.             case System.Collections.Specialized.NotifyCollectionChangedAction.Add:  
  8.                 _dbSet.Add((TEntity)e.NewItems[0]);  
  9.                 break;  
  10.             case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:  
  11.                 _dbSet.Remove((TEntity)e.OldItems[0]);  
  12.                 break;  
  13.             default:  
  14.                 break;  
  15.         }  
  16.     };  
  17. }  

This method is necessary because we should return a part of DbSet property Local information only, for it we create a new ObservableCollection with the filter data and in this moment the Local property unlink it. The RelinkObservableCollection relinked the ObservableCollection changes with the DbSet.

In use,

  1. [TestMethod]  
  2. public void GetData_OK()  
  3. {  
  4.     Expression < Func < FootballClub, bool >> filter = a => a.Name == "Real Madrid C. F.";  
  5.     ObservableCollection < FootballClub > result = instance.GetData(filter);  
  6.     Assert.IsNotNull(result);  
  7.     Assert.IsTrue(result.Count == 1);  
  8. }  

SaveChanges / SaveChangesAsync

The method SaveChanges/SaveChangesAsync preserves the ObservableCollection Local property in Database.

  1. public int SaveChanges() {  
  2.     var result = _dbContext.SaveChanges();  
  3.     return result;  
  4. }  
  5. public Task < int > SaveChangesAsync() {  
  6.     return _dbContext.SaveChangesAsync();  
  7. }  

In action,

  1. [TestMethod]  
  2. public void SaveChanges_OK() {  
  3.     ObservableCollection < FootballClub > data = instance.All();  
  4.     data.Add(new FootballClub {  
  5.         CityId = 1,  
  6.             Name = "New Team",  
  7.             Members = 0,  
  8.             Stadium = "New Stadium",  
  9.             FundationDate = DateTime.Today  
  10.     });  
  11.     int result = instance.SaveChanges();  
  12.     int expected = 1;  
  13.     RemovedInsertRecords();  
  14.     Assert.AreEqual(expected, result);  
  15. }  

HasChanges / HasChangesAsync

The method HasChanges/HasChangesAsync verifies if the DbSet property has been modified. In WPF applications this is very practical in conjunction of Commands for enabled or disabled save buttons.

  1. public bool HasChanges()  
  2. {  
  3.     var result = _dbContext.ChangeTracker.Entries<TEntity>()  
  4.                     .Any(a => a.State == EntityState.Added   
  5.                             || a.State == EntityState.Deleted   
  6.                             || a.State == EntityState.Modified);  
  7.    
  8.     return result;  
  9. }  
  10.    
  11. public Task<bool> HasChangesAsync()  
  12. {  
  13.     return Task.Run(() =>  
  14.     {  
  15.         return HasChanges();  
  16.     });  
  17. }  

The method verified the ChangeTracker property search rows in state: Added, Deleted or Modified.

In action,

  1. [TestMethod]  
  2. public void HasChanges_OK() {  
  3.     ObservableCollection < FootballClub > data = instance.All();  
  4.     data.Add(new FootballClub {  
  5.         CityId = 1,  
  6.             Name = "New Team",  
  7.             Members = 0,  
  8.             Stadium = "New Stadium",  
  9.             FundationDate = DateTime.Today  
  10.     });  
  11.     bool result = instance.HasChanges();  
  12.     Assert.IsTrue(result);  
  13. }  

Extracting the Interface

Once this has been done, we will extract the Interface.

Entity Framework Generic Repository

Result

  1. public interface IConGenericRepository<TEntity> : IDisposable where TEntity : class  
  2. {  
  3.     ObservableCollection<TEntity> All();  
  4.     Task<ObservableCollection<TEntity>> AllAsync();  
  5.     ObservableCollection<TEntity> GetData(Expression<Func<TEntity, bool>> filter);  
  6.     Task<ObservableCollection<TEntity>> GetDataAsync(Expression<Func<TEntity, bool>> filter);  
  7.     TEntity Find(params object[] pks);  
  8.     Task<TEntity> FindAsync(object[] pks);  
  9.     int SaveChanges();  
  10.     Task<int> SaveChangesAsync();  
  11.     bool HasChanges();  
  12.     Task<bool> HasChangesAsync();  
  13. }  

We have translated the IDisposable implements to this interface.

WPF Example

The example making is the same as for Disconnected Repository, so that you can see it in the Disconnected article.

Thinking in our Connected Generic Repository, MainViewModel is a most important class. In our example, we interact directly with the data grid for three actions:

  • Insert .- For insert new row, we will fill the last empty data-grid row.
  • Update .- For update rows, we will click on y the datagrid cell for entry in edit mode, and we will modify data.
  • Delete .- For delete rows, we will select the datagrid row and press the ‘supr’ key.

    Entity Framework Generic Repository

In the following, we will show the classes (ViewModels) where we use the Connected Generic Repository in the WPF project.

  1. public class MainViewModel: ViewModelBase, IDisposable {  
  2.     private readonly IConGenericRepository < FootballClub > _repository;  
  3.     public ObservableCollection < FootballClub > Data {  
  4.         get;  
  5.         set;  
  6.     }  
  7.     private FootballClub _selectedItem;  
  8.     public FootballClub SelectedItem {  
  9.         get {  
  10.             return _selectedItem;  
  11.         }  
  12.         set {  
  13.             Set(nameof(SelectedItem), ref _selectedItem, value);  
  14.         }  
  15.     }  
  16.     public MainViewModel(IConGenericRepository < FootballClub > repository) {  
  17.         _repository = repository;  
  18.         Data = _repository.All();  
  19.     }  
  20.     public void Dispose() {  
  21.         _repository.Dispose();  
  22.     }  
  23.     public RelayCommand SaveCommand => new RelayCommand(SaveExecute, SaveCanExecute);  
  24.     private bool SaveCanExecute() {  
  25.         var result = _repository.HasChanges();  
  26.         return result;  
  27.     }  
  28.     private void SaveExecute() {  
  29.         Action callback = () => {  
  30.             var changes = _repository.SaveChanges();  
  31.             Messenger.Default.Send(new PopupMessage($ "It has been realized {changes} change(s) in Database."));  
  32.             CollectionViewSource.GetDefaultView(Data).Refresh();  
  33.         };  
  34.         Messenger.Default.Send(new PopupMessage("Do you want to make changes in DataBase ?", callback));  
  35.     }  
  36. }  

The class MainViewModel receives injected a IConGenericRepository<FootballClub> interface. In its constructor feed your namesake injects field and fills the ObservableCollection and uses All generic repository method. This class has a RelayCommand with name SaveCommand, this command uses two methods, Execute and CanExecute. For CanExecute method we will use the HasChanges repository method, this will provide enabled or disabled the save button and we will us to assure save without changes. The SaveExecuted method sends message to view for show messagebox, and it wait the messagebox answer to save data in database for SaveChanges repository method.

Extending ConGenericRepository

The connected world can be confusing. In the previous example, we could make serveral changes in the datagrid and as we were going to save the changes, we knew nothing of which rows are inserted or which rows are updated or deleted. For this reason, we will create a new datagrid column with this information. This column will be the row state.

Entity Framework Generic Repository

In the Entity Framework model class, we will create a new NotMapped property.

  1. private string _state;  
  2. [NotMapped]  
  3. public string State {  
  4.     get {  
  5.         return _state;  
  6.     }  
  7.     set {  
  8.         if (_state != value) {  
  9.             _state = value;  
  10.             OnPropertyChanged();  
  11.         }  
  12.     }  
  13. }  

This property will contain the all property general state. In Entity Framework initial version, all generates entities class had this property.

We will add the new specific generic repository connected, FutballClubConRepository

  1. public class FootballClubConRepository: ConGenericRepository < FootballClub > , IFootballClubConRepository {  
  2.     public FootballClubConRepository(DbContext dbContext): base(dbContext) {}  
  3.     public string GetState(FootballClub entity) {  
  4.         var stateEntity = _dbContext.Entry(entity).State;  
  5.         return stateEntity.ToString();  
  6.     }  
  7. }  

FutballClubConRepository should be inherits ConGenericRepository<TEntity> and implements a constructor base. Add the GetState method for advice the Entity Framework internal state.

We will Update MainViewModel

  1. public class MainViewModel : ViewModelBase, IDisposable  
  2. {  
  3.     private readonly IFootballClubConRepository _repository;  
  4.    
  5.     //private readonly IConGenericRepository<FootballClub> _repository;  
  6.     public ObservableCollection<FootballClub> Data { get; set; }  
  7.    
  8.    
  9.    
  10.     //public MainViewModel(IConGenericRepository<FootballClub> repository)  
  11.     public MainViewModel(IFootballClubConRepository repository)  
  12.     {  
  13.         _repository = repository;  
  14.    
  15.         Data = _repository.All();  
  16.    
  17.         ListenerChangeState(Data, _repository);  
  18.     }  
  19.    
  20.     private void ListenerChangeState(ObservableCollection<FootballClub> data, IFootballClubConRepository repository)  
  21.     {  
  22.         data.ToList().ForEach(a => ChangeStateRegister(a, repository));  
  23.    
  24.         data.CollectionChanged += (sender, e) =>  
  25.         {  
  26.             if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)  
  27.             {  
  28.                 var entity = e.NewItems[0] as FootballClub;  
  29.    
  30.                 entity.State = "Added";  
  31.             }  
  32.         };  
  33.     }  
  34.    
  35.     private void ChangeStateRegister(FootballClub entity, IFootballClubConRepository repository)  
  36.     {  
  37.         entity.PropertyChanged += (sender, e) =>  
  38.         {  
  39.             if (e.PropertyName != "State")  
  40.             {  
  41.                 entity.State = repository.GetState(entity);  
  42.             }  
  43.         };  
  44.     }  
  45.    
  46.     public void Dispose()  
  47.     {  
  48.         _repository.Dispose();  
  49.     }  
  50.    
  51.    
  52.     public RelayCommand SaveCommand => new RelayCommand(SaveExecute, SaveCanExecute);  
  53.    
  54.     private bool SaveCanExecute()  
  55.     {  
  56.         var result = _repository.HasChanges();  
  57.    
  58.         return result;  
  59.     }  
  60.    
  61.     private void SaveExecute()  
  62.     {  
  63.         Action callback = () =>  
  64.         {  
  65.             var changes = _repository.SaveChanges();  
  66.    
  67.             Messenger.Default.Send(new PopupMessage($"It has been realized {changes} change(s) in Database." ));  
  68.    
  69.             CollectionViewSource.GetDefaultView(Data).Refresh();  
  70.    
  71.             ResetDataStates(Data);  
  72.         };  
  73.    
  74.         Messenger.Default.Send(new PopupMessage("Has you make the changes in DataBase ?", callback));  
  75.     }  
  76.    
  77.     private void ResetDataStates(ObservableCollection<FootballClub> data)  
  78.     {  
  79.         data.ToList().ForEach(a => a.State = null);  
  80.     }  
  81. }  

We have added two private methods for registering changes ListenerChangedState, that registers the insert changes and ChangeStateRegister that register the modified changes.

Ultimately, we will review the class converter

  1. public class StateConverter : IMultiValueConverter  
  2. {  
  3.    
  4.     public ImageBrush _imgInsert;  
  5.     public ImageBrush _imgUpdate;  
  6.    
  7.    
  8.    
  9.     public StateConverter()  
  10.     {  
  11.         _imgInsert = Application.Current.FindResource("Inserted") as ImageBrush;  
  12.         _imgUpdate = Application.Current.FindResource("Edited") as ImageBrush;  
  13.     }  
  14.    
  15.    
  16.     public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)  
  17.     {  
  18.         if (values[0] == nullreturn null;  
  19.    
  20.         var valueStr = values[0].ToString();  
  21.    
  22.         switch (valueStr)  
  23.         {  
  24.             case "Added"   : return _imgInsert;  
  25.             case "Modified"return _imgUpdate;  
  26.         }  
  27.    
  28.         return null;  
  29.     }  
  30.    
  31.     public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)  
  32.     {  
  33.         throw new NotImplementedException();  
  34.     }  
  35. }  

This class transform the state description for the image description.

In action,

Entity Framework Generic Repository

Test Project

The test project still has the same structure as the one in the previous article, Generic Repository Disconnected. We add a new WPF project BuildingEFGRepository.WPF_Con with the new example.