将SQL DISTINCT with ORDER BY DESC转换为LINQ to Entities(将格式化日期绑定
本文关键字:Entities to 格式化 绑定 日期 LINQ 转换 DISTINCT SQL with ORDER | 更新日期: 2023-09-27 18:10:14
我需要填充一个ASP。NET DropDownList控件,具有不同的日期,以降序排列,格式化为mm/dd/yyyy。
不同的日期将从名为Inventory的SQL Server数据库表中的datetime字段ImportDate中提取。
下面的SQL语句将以正确的顺序和格式拉回正确的数据:
SELECT CONVERT(VARCHAR(10), X.DistinctImportDate , 101) AS ImportDate
FROM
(
SELECT DISTINCT(CONVERT(DATE, dbo.Inventory.ImportDate)) AS DistinctImportDate
FROM dbo.Inventory
) AS X
ORDER BY DistinctImportDate DESC
项目的数据访问层是一个实体框架5模型,它包含一个具有ImportDate属性的库存实体。
我需要做的是将上述SQL转换为实体框架5的c# LINQ到实体查询,并将结果绑定到ASP。. NET 下拉列表控件。关于如何最好地实现这一点,有什么想法吗?
解决方案:
这是我最终选择的解决方案(感谢COLD TOLD的引领)。下面的方法将以正确的顺序和格式返回正确的数据:
public static List<string> SelectDistinctImportDate()
{
using (var dbo = new DatabaseContext())
{
//get distinct dates from database in descending order
var data = (from c in dbo.Inventory
where c.ImportDate != null
select c.ImportDate ).Distinct().OrderByDescending(c => c.Value);
//create list of type string to return formatted results and bind to DropDownList
List<string> s = new List<string>();
//loop through all datetime objects returned from linq query
foreach (DateTime d in data)
{
//format each value and add to return object
s.Add(d.ToString("MM-dd-yyyy"));
}
//return the ordered and formatted list of distinct dates
return s;
}
}
上面的方法可以绑定到一个ASP。带有ObjectDataSource的. NET下拉列表,如下所示:
<asp:ObjectDataSource ID="odsDistinctImportDate" runat="server"
TypeName="MyLibrary.Inventory"
SelectMethod="SelectDistinctImportDate">
</asp:ObjectDataSource>
<asp:DropDownList ID="ddlDistinctImportDate" runat="server"
AppendDataBoundItems="True"
DataSourceID="odsDistinctImportDate">
</asp:DropDownList>
你可以使用linq,它有不同的扩展名,它可以像这样实现
var data=(from c in dbo.Inventory
select c.ImportDate).Distinct().OrderByDescending(c=>c.Value).ToList();