Facing issue when debug the code. It seems like everything is fine but don`t how to fix this

38 Views Asked by At
public IBaseRepository<TEntity, TIdentifier> GetRepository<TEntity, TIdentifier>(Expression<Func<TEntity, TIdentifier>> identifierExpression) where TEntity : class
{
    var entityType = typeof(TEntity);

    if (_repositories.ContainsKey(entityType))
    {
        return (IBaseRepository<TEntity, TIdentifier>)_repositories[entityType];
    }

    var identifierType = typeof(TIdentifier);

    var repositoryType = typeof(BaseRepository<,>).MakeGenericType(entityType, identifierType);
    var repositoryInstance = Activator.CreateInstance(repositoryType, context, identifierExpression);

    _repositories.Add(entityType, repositoryInstance);

    return (IBaseRepository<TEntity, TIdentifier>)repositoryInstance;
}

I am getting exception on the line :

var repositoryType = typeof(BaseRepository<,>).MakeGenericType(entityType, identifierType);

The exception is : GenericArguments[0], 'DataAccessLayer.EclareDBContext.MainPerson', on 'BuinessLogicLayer.Repositories.BaseRepository`2[T,TIdentifier]' violates the constraint of type 'T'.

I have defined the base repository like this :

 public class BaseRepository<T, TIdentifier> : IBaseRepository<T, TIdentifier> where T : class, IEntity<TIdentifier>

The IEntity is :

  public interface IEntity<T>
    {
        T Identifier { get; }
    }

Help me to come out of this exceptions.

1

There are 1 best solutions below

0
Jeff Do On

You can try:

var entityTypeArgument = entityType.GetGenericArguments().FirstOrDefault();
var identifierTypeArgument = identifierType.GetGenericArguments().FirstOrDefault();
if (entityTypeArgument != null && identifierTypeArgument != null)
{
    var repositoryType = typeof(BaseRepository<,>).MakeGenericType(entityTypeArgument, identifierTypeArgument);
}