Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we do object filtering in Entity Framework?

When defining an object context, using code first in entity framework, for example:

public class DomainContext : DbContext
{
    public DomainContext() { }
    public virtual DbSet<News> News { get; set; }
}

We all know that you can query "News" doing something like (for example, to get all news that were published today):

var ctx = new DomainContext();
ctx.News.Where(x => x.PublishedDate == DateTime.Now.Date)

But, and this is the question: Is there a way to apply a pre-defined filtering/condition to all queries that pass through ctx.News? Say that I wanted that all queries on ctx.News to have the "Published Today" filtering implicit applied?

like image 612
thr Avatar asked May 16 '11 20:05

thr


1 Answers

There is no way to add automatic condition (filter) to querying news. All posted examples work but only if you query News directly. If you for example loads navigation property pointing to News examples will fail.

EDMX solve this by conditional mapping but this leads to other very bad disadvantages. Conditional mapping is fixed (cannot be changed without rebuilding model) and you can have only single condition for each type - it is like TPH degraded to single entity type. Moreover conditions defined in conditional mapping probably cannot work with "Today". Conditional mapping is not available in code-first approach.

like image 112
Ladislav Mrnka Avatar answered Sep 22 '22 15:09

Ladislav Mrnka