Instantiate generic repository dynamically and how to add entity base class to Entity Framework
<p>Following is the implementation of repository pattern using EF6. I want to use the generic repository in the following way thereby removing the need to create repository for every type</p>

<pre><code>_unitOfWork.Repository(entityName).Insert(entityName)

public interface IRepository&lt;T&gt; where T : class
{
    //--Search Operations
    IEnumerable&lt;T&gt; Get();
    T GetByID(object id);
    void Insert(T entity);
    void Delete(object id);
    void Delete(T entityToDelete);
    void Update(T entityToUpdate);
}
</code></pre>

<p>I have created a base class that all entities will inherit. The intent of this bases class is so that i can refer all entities with this base class.</p>

<pre><code>public class IRepositoryEntity
{
}
</code></pre>

<p>Following is the Entity Framework generated code, I have inherited this entity from <code>IRepositoryEntity</code></p>

<pre><code>public partial class Client_Entity: IRepositoryEntity
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Client_Entity()
    {
    }

    public int Id { get; set; }
}
</code></pre>

<p>Following is the generic repository</p>

<pre><code>public class GenericRepository&lt;IRepositoryEntity&gt; : IRepository&lt;IRepositoryEntity&gt; where IRepositoryEntity : class
{
    #region Private member variables...
    internal ConsularDB_March2016Entities Context;
    internal DbSet&lt;IRepositoryEntity&gt; DbSet;
    #endregion

    #region Public Constructor...
    /// &lt;summary&gt;
    /// Public Constructor,initializes privately declared local variables.
    /// &lt;/summary&gt;
    /// &lt;param name="context"&gt;&lt;/param&gt;
    public GenericRepository(ConsularDB_March2016Entities context)
    {
        this.Context = context;
        this.DbSet = context.Set&lt;IRepositoryEntity&gt;();
    }
    ///// &lt;summary&gt;
    ///// Public Constructor,initializes privately declared local variables.
    ///// &lt;/summary&gt;
    ///// &lt;param name="context"&gt;&lt;/param&gt;
    //public GenericRepository()
    //{
    //    this.Context = context;
    //    this.DbSet = context.Set&lt;IRepositoryEntity&gt;();
    //}
    #endregion

    #region Public member methods...

    /// &lt;summary&gt;
    /// generic Get method for Entities
    /// &lt;/summary&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public  IEnumerable&lt;IRepositoryEntity&gt; Get()
    {
        IQueryable&lt;IRepositoryEntity&gt; query = DbSet;
        return query.ToList();
    }
}
</code></pre>

<p>Following is the <code>IUnitOfWork</code> interface and its implementation</p>

<pre><code>public interface IUnitOfWork
{
    #region Properties
    GenericRepository&lt;Client_Entity&gt; ClientRepository { get; }
    #endregion

    #region Public methods
    /// &lt;summary&gt;
    /// Save method.
    /// &lt;/summary&gt;
    void Save();
    GenericRepository&lt;IRepositoryEntity&gt; Repository(IRepositoryEntity entity);
    #endregion
}

/// &lt;summary&gt;
/// Unit of Work class responsible for DB transactions
/// &lt;/summary&gt;
public class UnitOfWork : IDisposable, IUnitOfWork
{
    #region Private member variables...

    private March2016Entities _context = null;
    private GenericRepository&lt;Client_Entity&gt; _clientRepository;
    #endregion

    public UnitOfWork()
    {
        _context = new March2016Entities();
    }

     #region Public member methods...
    /// &lt;summary&gt;
    /// Save method.
    /// &lt;/summary&gt;
    public void Save()
    {
        try
        {
            _context.Configuration.ValidateOnSaveEnabled = false;
            _context.SaveChanges();
        }
        catch (DbUpdateConcurrencyException ex)
        {
            var context = ((IObjectContextAdapter)_context).ObjectContext;
            var refreshobjects = _context.ChangeTracker.Entries().Select(c =&gt; c.Entity).ToList();
            context.Refresh(System.Data.Entity.Core.Objects.RefreshMode.StoreWins, refreshobjects);
            _context.SaveChanges();
        }
        catch (DbEntityValidationException e)
        {

            var outputLines = new List&lt;string&gt;();
            foreach (var eve in e.EntityValidationErrors)
            {
                outputLines.Add(string.Format("{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:", DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
                foreach (var ve in eve.ValidationErrors)
                {
                    outputLines.Add(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
                }
            }
            System.IO.File.AppendAllLines(@"C:\errors.txt", outputLines);

            throw e;
        }

    }

    #endregion

    #region Implementing IDiosposable...

    #region private dispose variable declaration...
    private bool disposed = false;
    #endregion

    /// &lt;summary&gt;
    /// Protected Virtual Dispose method
    /// &lt;/summary&gt;
    /// &lt;param name="disposing"&gt;&lt;/param&gt;
    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                Debug.WriteLine("UnitOfWork is being disposed");
                _context.Dispose();
            }
        }
        this.disposed = true;
    }

    /// &lt;summary&gt;
    /// Dispose method
    /// &lt;/summary&gt;
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    #endregion
    #region GenericMembers
    Dictionary&lt;string, GenericRepository&lt;IRepositoryEntity&gt;&gt; repostories = new Dictionary&lt;string, GenericRepository&lt;IRepositoryEntity&gt;&gt;();

    /// &lt;summary&gt;
    /// Generic Repository method which checks the repository is available if not,
    /// it sets it up.
    /// &lt;/summary&gt;
    /// &lt;param name="entity"&gt;Entity&lt;/param&gt;
    /// &lt;returns&gt;Repository to use.&lt;/returns&gt;
    public GenericRepository&lt;IRepositoryEntity&gt; Repository(IRepositoryEntity entity)
    {
        string index = entity.GetType().ToString();

        if (!repostories.ContainsKey(index))
        {

            //Reflections to create the repoositiory if it is not needed.
            Type type1 = typeof(GenericRepository&lt;IRepositoryEntity&gt;);
            Type[] typeArgs = { entity.GetType() };

            Type constructed = type1.MakeGenericType(typeArgs);
            object o = Activator.CreateInstance(constructed, this._context);

            //if (o is GenericRepository&lt;IRepositoryEntity&gt;)
            //{
            object genericRepo = (object)o;
            var rep = (GenericRepository&lt;IRepositoryEntity&gt;)genericRepo;
            //rep.Context = this._context;
            repostories.Add(index, rep);
            //}
        }
        return this.repostories[index];
    }
    #endregion  
}
</code></pre>

<p>I am trying to create a list of <code>GenericRepository</code> dynamically in the following function </p>

<pre><code>public GenericRepository&lt;IRepositoryEntity&gt; Repository(IRepositoryEntity entity)
</code></pre>

<p>while creating the instance, it is throwing the following exception</p>

<blockquote>
  <p>An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code</p>
  
  <p>Additional information: GenericRepository`1[IRepositoryEntity] is not a GenericTypeDefinition. MakeGenericType may only be called on a type for which Type.IsGenericTypeDefinition is true.</p>
</blockquote>

<p>I understand the exception, however not sure on how can I change the implementation so that i am able to achieve the desired functionality. Also how can I add <code>IRepositoryEntity</code> to EF model because it says it is not part of the model.</p>

<pre><code>public void ValidateGenericEntityInsert(IRepositoryEntity entityName)
{
        IRepositoryEntity entity = (IRepositoryEntity)Activator.CreateInstance(entityName);
        _unitOfWork.Repository(entityName).Insert(entityName);

        // int generatedId = GetPropertyFromEntity(entity, en =&gt; en.Id);
        int generatedId = (int)GetPropertyFromEntity(entityName, "Id");

        Assert.That(generatedId, Is.GreaterThan(0));
}
</code></pre>