Greg Gum Greg Gum - 3 months ago 16
C# Question

How to cast DbSet<Team> to DbSet<EntityBase>

I have a RepositoryBase class that does some basic operations on Entities which are derived from EntityBase.

public class RepositoryBase
{
private ApplicationDbContext _context;
public DbSet<EntityBase> DbSet;

public RepositoryBase(ApplicationDbContext context )
{
_context = context;

}

public List<EntityBase> List(int entityStatus)
{
return DbSet.Where(a => a.EntityStatusId == entityStatus).OrderBy(a => a.Name).ToList();
}


public EntityBase GetTeamDetails(int id)
{
return this.DbSet.FirstOrDefault(a => a.Id == id);

}

internal List<EntityBase> ListActive()
{
return DbSet.Where(a => a.EntityStatusId == (int)EntityStatus.Active).ToList();
}

internal List<EntityBase> ListTrashed()
{
return DbSet.Where(a => a.EntityStatusId == (int)EntityStatus.Trashed).ToList();
}

public void SaveProject(EntityBase item)
{
DbSet.Attach(item);
_context.Entry(item).State = EntityState.Modified;
_context.SaveChanges();

}

public List<EntityBase> ListArchived()
{
return DbSet.Where(a => a.EntityStatusId == (int)EntityStatus.Archived).ToList();
}

internal List<EntityBase> Search(string searchText)
{
return DbSet.Where(a => a.Name.Contains(searchText)).ToList();
}

public EntityBase New(EntityBase item)
{
DbSet.Add(item);
_context.SaveChanges();
return item;
}
}


The issue I am having is passing the DbSet to the base class. This is what I want to do:

public TeamRepository(ApplicationDbContext context) : base(context)
{
this.DbSet = (DbSet<EntityBase>)context.Teams;
}


However, this does not compile. It says it cannot cast from DbSet to DbSet even through Team is derived from EntityBase.

How do I make this cast?

Answer

you can make it generic this way:

public class BaseRepository<T> : IBaseRepository<T> where T : EntityBase
{
    public BaseRepository(CustomDBContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context", "The given parameter cannot be null.");
        }
        this.Context = context;
    }

    protected ApplicationDbContext Context
    {
        get;
        private set;
    }

    public T Get(int id)
    {
        return Context.Set<T>().Find(id);
    }


   .....

}