在linq中将字符串转换为int

时间:2017-09-28 11:14:58

标签: c# sql-server linq

我有一个表tblcatalogue,并且有一个数据类型为varchar的列classid。我想要一个包含orderby classid的结果集,但是问题是使用orderid的顺序没有给出所需的结果。所以我试图将classid转换为整数喜欢

$("#FormAdd").submit(function(e) {
    $.ajax({
           type: "POST",
           url: 'validate/action.php',
           data: $(this).serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // data successfully added
           }
         });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});

$("#FormEdit").submit(function(e) {
    $.ajax({
           type: "POST",
           url: 'validate/action.php',
           data: $(this).serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // data successfully updated
           }
         });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});

$("#FormDelete").submit(function(e) {
    $.ajax({
           type: "POST",
           url: 'validate/action.php',
           data: $(this).serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // data successfully deleted
           }
         });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});

但我正在获取像

这样的SQL查询
var query= itemRepository.GetAll();  
results = query.ToList().OrderBy(x=> Convert.ToInt32(x.ClassId));   

我想转换sql查询,如

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[SubjectId] AS [SubjectId], 
[Extent1].[SeriesId] AS [SeriesId], 
[Extent1].[Title] AS [Title], 
[Extent1].[Author] AS [Author], 
[Extent1].[ISBN] AS [ISBN], 
[Extent1].[Edition] AS [Edition], 
[Extent1].[Price] AS [Price], 
[Extent1].[Discount] AS [Discount], 
[Extent1].[BoardId] AS [BoardId], 
[Extent1].[ClassId] AS [ClassId]
FROM [dbo].[tblCataLogue] AS [Extent1]
ORDER BY [Extent1].[ClassId] ASC

因为它提供了正确的结果集

1 个答案:

答案 0 :(得分:2)

使用ToList()时,您正在对数据库执行查询,因此不会进行所需的排序。删除ToList(),order by子句也将被翻译为sql:

results = query.OrderBy(x=> Convert.ToInt32(x.ClassId)).ToList();   

对于进行中的错误,linq提供程序不支持Convert.ToInt32,并且无法将其转换为sql。因此,您应该做以下两件事之一:

  1. 从一开始,首先将数据检索到内存中(使用ToList() / AsEnumerable())然后转换
  2. 将数据库中的列更改为int-IMO类型,因为您的数据是一个数字,它应该在任何情况下都表示为..