Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8967451
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T17:14:46+00:00 2026-06-15T17:14:46+00:00

I am working on updating to a more manageable repository pattern in my MVC

  • 0

I am working on updating to a more manageable repository pattern in my MVC 4 project that uses Entity Framework code first. I’ve integrated a generic base repository class that will do basic CRUD operations so I don’t have to implement these in each repository I create. I have ran into an issue where my All method needs to filter there query by a deleted flag if the entity is a type of TrackableEntity. Since the Entity is generic in the base repository I am attempting to cast is to a type of TrackableEntity in the where which just results in the following error message.

The ‘TypeAs’ expression with an input of type ‘NameSpace.Models.ClientFormField’ and a check of type ‘NameSpace.Models.TrackableEntity’ is not supported. Only entity types and complex types are supported in LINQ to Entities queries.

This error makes complete since and I understand why the code I have is not working but I am trying to find a way to filter out deleted items without having to override this method in all of my repositories. The code I have for my All method is below.

public virtual IEnumerable<T> All()
{
    if (typeof(T).IsSubclassOf(typeof(TrackableEntity)))
        return dbSet.Where(e => !(e as TrackableEntity).IsDeleted).ToList();

    return dbSet.ToList();
}

I know that I can do the following

public virtual IEnumerable<T> All(Expression<Func<T, bool>> predicate = null)
{
    if (predicate != null)
        return dbSet.Where(predicate).IsDeleted).ToList();

    return dbSet.ToList();
}

And then add this to all of my repositories

public override IEnumerable<CaseType> All(Expression<Func<CaseType,bool>> predicate = null)
{
    if (predicate == null)
        predicate = e => !e.IsDeleted;
    return base.All(predicate);
}

The problem I have with this is that I am duplicating code, this is basically a copy and paste into all of my repositories which defeats the purpose of changing to this new repository pattern. I made the switch to end duplicated code in my repositories.

Here is an example of one of my entities.

public class CaseType : TrackableEntity, IValidatableObject
{
    public int Id { get; set; }
    public string Name { get; set; }

    public bool InUse { get; set; }

    public bool IsValid { get { return !this.Validate(null).Any(); } }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (String.IsNullOrEmpty(Name))
            yield return new ValidationResult("Case Type name cannot be blank", new[] { "Name" });

        //Finish Validation Rules
    }
}

And the TrackableEntity

public abstract class TrackableEntity
{
    public bool Active { get; set; }
    public bool IsDeleted { get; set; }
    public virtual User CreatedBy { get; set; }
    public virtual User ModifiedBy { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }
}

Any help on this would be much appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T17:14:47+00:00Added an answer on June 15, 2026 at 5:14 pm

    I finally got a solution working that I am happy with. I ended up making 2 generic repositories. One that is the base repository which deals with all of the calls to the database for my BaseEntity which all entities inherit from. Then I made my 2nd generic repo which is inherits BaesEntity and overrides a few methods to handle the needs of my TrackableEntities. In the end this does what I want by handling the filtering of soft deleted items from within the repo and also gives me more flexibility with the TrackableEntity.

    BaseRepository –

    public class BaseRepository<T> : IBaseRepository<T> where T : BaseEntity
    {
        private readonly IAppDb _db;
        private readonly IDbSet<T> _dbSet;
    
        public BaseRepository(IAppDb db)
        {
            _db = db;
            _dbSet = Lwdb.Set<T>();
        }
    
        protected IAppDb Lwdb
        {
            get { return _db; }
        }
    
        #region IBaseRepository<T> Members
    
        public virtual T GetById(int id)
        {
            return _dbSet.Find(id);
        }
    
        public virtual T Add(T entity)
        {
            _dbSet.Add(entity);
            _db.Commit();
            return entity;
        }
    
        public virtual bool Any(Expression<Func<T, bool>> expression)
        {
            return _dbSet.Any(expression);
        }
    
        public virtual void Delete(T entity)
        {
            _dbSet.Remove(entity);
            _db.Commit();
        }
    
        public virtual IEnumerable<T> All()
        {
            return _dbSet.ToList();
        }
    
        public virtual T Update(T entity, bool attachOnly = false)
        {
            _dbSet.Attach(entity);
            _db.SetModified(entity);
            if (!attachOnly) _db.Commit();
            return entity;
        }
    
        #endregion
    
        protected User GetCurrentUser()
        {
            return
                _db.Set<User>().Find(HttpContext.Current != null ? ((User) HttpContext.Current.Session["User"]).Id : 1);
        }
    

    BaseTrackableEntityRepository –

    public class BaseTrackableEntityRepository<T> : BaseRepository<T>, IBaseTrackableEntityRepository<T>
        where T : TrackableEntity
    {
        private readonly IAppDb _db;
        private readonly IDbSet<T> _teDB;
    
        public BaseTrackableEntityRepository(IAppDb db)
            : base(db)
        {
            _db = db;
            _teDB = _db.Set<T>();
        }
    
        #region IBaseTrackableEntityRepository<T> Members
    
        public virtual T SetDeleteFlag(int id)
        {
            var entity = _teDB.Find(id);
            if (entity == null) return null; //throw exception
            entity.IsDeleted = true;
            entity.DateModified = DateTime.Now;
            entity.ModifiedBy = GetCurrentUser();
            return Update(entity);
        }
    
        public override IEnumerable<T> All()
        {
            return _teDB.Where(e => !e.IsDeleted).ToList();
        }
    
        public override T Add(T entity)
        {
            var curUser = GetCurrentUser();
            entity.CreatedBy = curUser;
            entity.ModifiedBy = curUser;
            entity.DateCreated = DateTime.Now;
            entity.DateModified = DateTime.Now;
            entity.Active = true;
            entity.IsDeleted = false;
            _teDB.Add(entity);
            _db.Commit();
            return entity;
        }
    
        public override T Update(T entity, bool attachOnly = false)
        {
            InsertTeData(ref entity);
            entity.ModifiedBy = GetCurrentUser();
            entity.DateModified = DateTime.Now;
            _teDB.Attach(entity);
            _db.SetModified(entity);
            if (!attachOnly) _db.Commit();
            return entity;
        }
    
        public virtual T SetStatus(int id, bool status)
        {
            var entity = _teDB.Find(id);
            if (entity == null) return null;
            entity.Active = status;
            return Update(entity);
        }
    
        #endregion
    
        private void InsertTeData(ref T entity)
        {
            if (entity == null || entity == null) return;
            var dbEntity = GetById(entity.Id);
            if (dbEntity == null) return;
            _db.Detach(dbEntity);
            entity.CreatedBy = dbEntity.CreatedBy;
            entity.DateCreated = dbEntity.DateCreated;
            entity.ModifiedBy = dbEntity.ModifiedBy;
            entity.DateModified = dbEntity.DateModified;
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm working on updating a project which uses the following code to place a
We are working on updating a code project that has become very messy over
I'm currently working on my first MVC project which is nothing more than a
I'm working on a project updating their WinForms application UI to be more consistent
I'm working on a project that requires a fair bit of inserting/updating rows in
I am currently working on a project that uses JPA (Toplink, currently) for its
So I'm working on updating a large project from really old C++/Carbon code, and
I'm working with a code base that is new to me, and it uses
I’m working on an app with an AIR3 iOS native extension that uses Accelerate.framework
While working on HTML, CSS (and more) like changing the code and refreshing the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.