Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have Entity Framework return related objects with some defaults?

Say I have Project and Task EF Code first classes

public class Project
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Task> Tasks { get; set; }
    }

    public class Task
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int ProjectId { get; set; }
        public bool IsDeleted {get; set;}
        public virtual Project Project { get; set; }
    }

Say I have

public void SomeAction()
{
Project p= repository.GetById(1);
var tasks = p.Tasks;
//var tasks = p.Tasks.Where(t=>t.IsDeleted==false);
}

I would like that my Tasks property on the Project class will always perform that filter on IsDeleted and just return that subset ... to avoid having to write that condition all over the place...

Any recommendations?

Edit:

Im using EF Code First

like image 782
nacho10f Avatar asked Aug 03 '11 19:08

nacho10f


People also ask

How do you load related entities in EF?

Entity Framework supports the following three methods to load related data. In Eager Loading, all relevant data for an entity is loaded at the time of the query of the entity in the context object. Eager Loading can be done by using the "Include" method. To perform Eager Loading, Lazy Loading must be disabled.

How do I enable eager loading in Entity Framework?

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by use of the Include method. For example, the queries below will load blogs and all the posts related to each blog. Include is an extension method in the System.

What is eager loading in EF core?

Eager loading means that the related data is loaded from the database as part of the initial query. Explicit loading means that the related data is explicitly loaded from the database at a later time.


1 Answers

Add a discriminator to your model in the OnModelCreating method

modelBuilder.Entity<TEntity>().Map(m => m.Requires("IsDeleted").HasValue(false));

Caveats

  • You can no longer load deleted items (unless you map IsDeleted true to another entity, then you may lose your automatic filtering)
  • The poco class cannot have the IsDeleted property (discriminators cannot be mapped)
  • because the IsDeleted cannot be mapped you need to run raw SQL to delete the entity in the first place.
like image 139
Betty Avatar answered Sep 23 '22 17:09

Betty