How can we filter objects in the Entity Framework?

When determining the context of an object, first using the code in the entity structure, for example:

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

We all know that you can request "News" by doing something like (for example, to receive all the news that was 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 predefined filtering / condition to all queries passing through ctx.News? Tell me, what did I want for all requests to ctx.Newsbe applied to the "Published today" filtering?

+5
source share
4 answers

() . , News . , , , News, .

EDMX , . ( ), - TPH, . , , , , "". .

+3

, DbSet<News>, . , , :

public virtual IEnumerable<News> TodaysNews
{
    get { return News.WHere(n => n.PublishDate == DateTime.Today); } 
}

, , , :

var todaysGoodNews = from n in ctx.TodaysNews
                     where n.IsGood == true
                     select n;

, , , . , , IEnumerable<>, - (IQueryable<>, ?).

Edit:

. , /. , , ? TodaysNews - .

+2

:

public IEnumerable<News> TodaysNews
{
    get
    {
        return this.News.Where(x => x.PublishedDate == DateTime.Now.Date);
    }
}

//etc .

Update:

If you can't just use a pre-filtered query, another option is to create a view in your database and match your entity with that view. The view may be based on the current date.

0
source

I have the same problem and I found this: EntityFramework.Filters . This post shows how to use it.

0
source

All Articles