Generic Repository with SQLite and SQL Compact Databases

Posted by Andrew Petersen on Programmers See other posts from Programmers or by Andrew Petersen
Published on 2013-06-29T12:46:06Z Indexed on 2013/06/29 16:29 UTC
Read the original article Hit count: 377

I am creating a project that has a mobile app (Xamarin.Android) using a SQLite database and a WPF application (Code First Entity Framework 5) using a SQL Compact database. This project will even eventually have a SQL Server database as well. Because of this I am trying to create a generic repository, so that I can pass in the correct context depending on which application is making the request.

The issue I ran into is my DataContext for the SQL Compact database inherits from DbContext and the SQLite database inherits from SQLiteConnection. What is the best way to make this generic, so that it doesn't matter what kind of database is on the back end?

This is what I have tried so far on the SQL Compact side:

    public interface IRepository<TEntity>
    {
        TEntity Add(TEntity entity);
    }

    public class Repository<TEntity, TContext> : IRepository<TEntity>, IDisposable
                                    where TEntity : class
                                    where TContext : DbContext
    {
           private readonly TContext _context;

           public Repository(DbContext dbContext)
           {
                 _context = dbContext as TContext;
           }

           public virtual TEntity Add(TEntity entity)
           {
                 return _context.Set<TEntity>().Add(entity);
           }
    }

And on the SQLite side:

    public class ElverDatabase : SQLiteConnection
    { 
         static readonly object Locker = new object();
         public ElverDatabase(string path) : base(path)
         {
                CreateTable<Ticket>();
         }

         public int Add<T>(T item) where T : IBusinessEntity
         {
                lock (Locker)
                {
                   return Insert(item);
                }
         }
     }

© Programmers or respective owner

Related posts about c#

Related posts about architecture