user251291
user251291

Reputation:

C# Linq query with where clause query containing a dynamic variable

I have a entity object in c#. It queries a database table called FBApi. The table stores an integer year and integer month. I have function that needs to return all records greater than the passed in parameters.

public query(int myYear, int myMonth){
   var context = new MCSSUtility.Entities();
   return context.FBApis.Where(p => p.month == month && p.year == year);
}

I was thinking of converting the integers to a DateTime object, but i am not sure how to dynamically convert the where clause to Datetime variable?

public query(int myYear, int myMonth){
   DateTime my = new DateTime(myYear,myMonth,1);
   var context = new MCSSUtility.Entities();
   return context.FBApis.Where(p => new DateTime(p.year,p.month,1) >= my);
}

Upvotes: 0

Views: 545

Answers (2)

petro.sidlovskyy
petro.sidlovskyy

Reputation: 5093

Please try this one:

            public query(int myYear, int myMonth){
               DateTime my = new DateTime(myYear,myMonth,1);
               var context = new MCSSUtility.Entities();
               return context.FBApis.Where(p => EntityFunctions.CreateDateTime(p.year, p.month, 1, 0, 0, 0)  >= my);
            }

Upvotes: 3

BlackjacketMack
BlackjacketMack

Reputation: 5692

Try first selecting an anonymous object with two properties: your FBApi object and your constructed datetime:

return context.FBApis
.Select(s=>new{MyFBAPIObject=s,MyDateTime=newDateTime(s.Year,s.Month,1)})
.Where(w=>w.MyDateTime>=my)
.Select(s2=>s2.MyFBAPIObject);

Upvotes: 0

Related Questions