简体   繁体   English

C#Linq查询,其中where子句查询包含动态变量

[英]C# Linq query with where clause query containing a dynamic variable

I have a entity object in c#. 我在C#中有一个实体对象。 It queries a database table called FBApi. 它查询名为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? 我当时正在考虑将整数转换为DateTime对象,但不确定如何将where子句动态转换为Datetime变量?

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);
}

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);
            }

Try first selecting an anonymous object with two properties: your FBApi object and your constructed datetime: 首先尝试选择一个具有两个属性的匿名对象:FBApi对象和构造的日期时间:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM