【发布时间】:2015-12-29 11:58:38
【问题描述】:
我有数据库表调用AB_Product,它有一个DateTime 字段调用CreatedDate
- 一旦用户输入
publishdatefrom作为日期,我想列出所有CreatedDate高于publishdatefrom的产品 - 一旦用户输入
publishdateto,我想列出所有产品CreatedDate低于publishdatefrom - 一旦用户输入
publishdateto和publishdatefrom,我想要 列出CreatedDate之间的所有产品publishdatefrom和publishdateto
我有以下方法可以根据publishdatefrom 和publishdateto 过滤器检索产品。
[HttpGet]
public JsonResult Fetch_Products(DateTime? publishdatefrom, DateTime? publishdateto)
{
IEnumerable<ProductCollection> products = (from P in db.AB_Product
join S in db.AB_Subsidary on P.Subsidary_ID equals S.SubsidaryID
select new ProductCollection
{
Product_ID = P.ProductID,
Product_Name_En = P.ProductTitleEn,
Product_Name_Ar = P.ProductTitleAr,
ProductType_ID = P.ProductTypeID,
ProductCategory_ID = P.ProductCategoryID,
Susidary_ID = P.Subsidary_ID,
Country_ID = S.Country,
CreatedDate = S.CreatedDate
}).ToList();
if (publishdatefrom.HasValue & !(publishdateto.HasValue))
{
DateTime d1 = publishdatefrom.Value.Date;
products = products.Where(p => p.CreatedDate >= d1);
}
if (!(publishdatefrom.HasValue) & publishdateto.HasValue)
{
DateTime d1 = publishdateto.Value.Date;
products = products.Where(p => p.CreatedDate < d1);
}
if (publishdatefrom.HasValue & publishdateto.HasValue)
{
DateTime d1 = publishdatefrom.Value.Date;
DateTime d2 = publishdateto.Value.Date;
products = products.Where(p => p.CreatedDate >= d1 | p.CreatedDate < d2);
}
var data = products.Select(p => new
{
Product_ID = p.Product_ID,
Product_Name_En = p.Product_Name_En,
Product_Name_Ar = p.Product_Name_Ar,
});
return Json(data, JsonRequestBehavior.AllowGet);
}
但是当它同时具有 publishdatefrom 和 publishdateto 过滤器的值时,我可以获得结果,如果它只有 publishdatefrom 或 publishdateto 我看不到任何结果。
我在这里错过了什么。?
我也尝试这样做
if (publishdatefrom.HasValue & !(publishdateto.HasValue))
{
DateTime d1 = publishdatefrom.Value.Date;
DateTime d2 = d1.AddDays(1);
products = products.Where(p => p.CreatedDate >= d1);
}
if (!(publishdatefrom.HasValue) & publishdateto.HasValue)
{
DateTime d1 = publishdateto.Value.Date;
DateTime d2 = d1.AddDays(1);
products = products.Where(p => p.CreatedDate >= d1 && p.CreatedDate < d2);
}
但是当它只有一个值时,什么都没有列出。
【问题讨论】:
-
你试过调试这个吗?
-
是的,我可以看到
Empty : Enumaration yielded no result -
所以您在
Where之前的列表中有实体,但之后没有。我说的对吗? -
您是否尝试手动比较过滤日期 (
d1) 与您的每个产品CreatedDate?
标签: c# json asp.net-mvc linq razor