I have a generic repository and i want to filter the data on Get in the generic repository. This method get the data and then other get methods call and return data
private IQueryable<T> fetchData(Expression<Func<T, bool>> filter)
{
IQueryable<T> query = dbSet;
if (filter != null) query = query.Where(filter);
}
This is the DbSet
private readonly IDbSet<T> dbSet;
and the class implemention is
public class Repository<T> : IRepository<T> where T : class
These are the classes and interfaces on Model class
public interface IEntity<T>
{
T Id { get; set; }
}
public interface IAuditableEntity
{
bool IsDeleted { get; set; }
}
public abstract class Entity<T> : IEntity<T>
{
[Key]
public virtual T Id { get; set; }
}
public abstract class AuditableEntity : Entity<string>, IEntity<string>, IAuditableEntity
{
public bool IsDeleted { get; set; }
}
[Table("Contact")]
public class Contact : AuditableEntity
{
[Required]
[StringLength(250)]
public string FirstName { get; set; }
[StringLength(250)]
public string MiddleName { get; set; }
[Required]
[StringLength(250)]
public string LastName { get; set; }
}
Now i want to filter the data in fetchData method so that only those records return which are deleted == false as this is a common functionality and should be implemented in repository base level not on individual repository or business logic classes.
The problem is that once i cast IQueryable<T> query to IQueryable<IAuditableEntity> query i cannot convert it back to IQueryable or for further filteration of data and return. I tried these but didn't work
var dbSetIAuditableEntity = dbSet as IQueryable<AuditableEntity>;
if (dbSetIAuditableEntity != null)
{
dbSetIAuditableEntity = dbSetIAuditableEntity.Where(d => d.IsDeleted == false);
query = (IQueryable<T>)((object)dbSetIAuditableEntity);
query = dbSet.Where(d => ((IAuditableEntity)d).IsDeleted == false);
}
Any suggestions to implement this functionality is generic repository
Edit
Actually all entities don't implement AuditableEntity some implement only IEntity<String> OR IEntity<int> and some implement nothing. It's not very good approach but this is the situation.
Edit 2
This is how i instantiate Generic repository By Autofac
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>));