0

I am using EF code first approch. Here is my context file.

 public class MyContext : DbContext
    {
        public DbSet<Contact> Contacts { get; set; }
        public DbSet<Contact_phone> Contact_phones{ get; set; }
    }

I want to add filter on bases of date on my context file, so that when i get data for any table i get for that specific date range only. Please suggest.

sagar43
  • 3,341
  • 3
  • 29
  • 49
  • It is a lil bit weird. Where do you want to take that Date ? – CodeNotFound Oct 08 '16 at 15:30
  • I'm assuming you are not talking about the relative easy filtering of your Contacts or Contact_Phones, but instead want something context wide for all tables? See [interceptors](https://msdn.microsoft.com/en-us/data/dn469464.aspx) – Steve Greene Oct 08 '16 at 15:31
  • @CodeNotFound like i want data from current year only so i set dates for this year only and on all points it gives me data from only this year where ever i access on the application level. – sagar43 Oct 08 '16 at 15:35
  • @SteveGreene yes i need it for all the tables – sagar43 Oct 08 '16 at 15:36
  • So you must look interceptors as @SteveGreene suggested. – CodeNotFound Oct 08 '16 at 16:06
  • @CodeNotFound Not getting what it says. – sagar43 Oct 08 '16 at 16:12
  • You could also use database views that wrap the date range logic, and map your entities to the views instead of the base tables. – sstan Oct 09 '16 at 04:01
  • @sstan I need it on my code view because i have to apply filter by user input. – sagar43 Oct 09 '16 at 14:07
  • There are a lot of options, some mentioned above. Try some code and report back what the issues are. Just start with simple [chained where clauses](http://stackoverflow.com/questions/11194/conditional-linq-queries) and build from there. – Steve Greene Oct 09 '16 at 15:46

1 Answers1

2

Disclaimer: I'm the owner of the project Entity Framework Plus

The library has a Query Filter which does exactly this scenario.

Under the hood, it uses interceptor (for EF6) as Steve Grene suggested.

Wiki: EF+ Query Filter

Filter Global

startDate = new DateTime(2015, 1, 1);
QueryFilterManager.Filter<Contacts>(q => q.Where(x => x.CreatedDate > startDate));

// SELECT * FROM Contacts WHERE CreatedDate > '2015-01-01'
var context = ctx.Contacts.ToList();

Filter By Instance

startDate = new DateTime(2015, 1, 1);
var ctx = new MyContext();
ctx.Filter<Contacts>(q => q.Where(x => x.CreatedDate > startDate));

// SELECT * FROM Contacts WHERE CreatedDate > '2015-01-01'
var context = ctx.Contacts.ToList();
Jonathan Magnan
  • 10,874
  • 2
  • 38
  • 60