linq to entity orderby奇怪的问题

时间:2010-09-05 14:12:47

标签: linq-to-entities sql-order-by

也许是愚蠢的问题,第一次使用linq实体(嗯,一般的linq)。

具有id(int),value(decimal),name(string)

的表

我需要的每条记录

id
list<string>
    id
    value
    name

以下作品精细

int pageSize=10
int pageIndex=2
var data = (from c in db.Customers
            orderby c.ID
            select new { c.ID, c.Value, c.Name }
             ).Skip(pageSize * pageIndex).Take(pageSize).ToArray();

但没有以我需要的方式组织数据。但结果如下:

1 100名A

2 300名B

3 200名C

4 100名D

以下让我做错了

int pageSize=10
int pageIndex=2
var data2 = (from c in db.Customers
             orderby c.ID
             select new
             {
                  id = c.ID,
                  cell = new List<string> { 
                     SqlFunctions.StringConvert((double)c.ID), 
                     SqlFunctions.StringConvert(c.Value), 
                     c.Name
                     }
             }
       ).Skip(pageSize * pageIndex).Take(pageSize).ToArray();

带来

1

     1        100     name A

2

     name B   300     2

3

     3        200     name C

4

     name D   100     4

依旧......

我无法理解为什么,以及如何在不编写长度代码的情况下解决它,我会跳过爱。

请帮助, 的Fabrizio

2 个答案:

答案 0 :(得分:1)

我不确切地知道您的代码无法正常工作,但请尝试使用ToString代替SqlFunction,如:

int pageSize = 10;
int pageIndex = 2;
var data = (from c in db.Customers
            orderby c.ID
            select new
            {
                c.ID, 
                cell = new List<string>{ c.ID.ToString(), c.Value.ToString(), c.Name }
            }).Skip(pageSize * pageIndex).Take(pageSize).ToArray();

var ordered = db.Customers.OrderBy(c => c.ID);
var page = orderedCustomers.Skip(pageIndex * pageSize).Take(pageSize);

var projection = page.Select(c => new
                 {
                     c.ID,
                     cell = new List<string> { c.ID.ToString(), c.Value.ToString(), c.Name }
                 }).ToArray();

更新:我看到你无法让Linq to Entity使用你的字符串。但你可以在本地做:)尝试:

var ordered = db.Customers.OrderBy(c => c.ID);
var page = orderedCustomers.Skip(pageIndex * pageSize).Take(pageSize);

var local = page.AsEnumerable();

var projection = local.Select(c => new
                 {
                     c.ID,
                     cell = new List<string> { c.ID.ToString(), c.Value.ToString(), c.Name }
                 }).ToArray();

答案 1 :(得分:0)

最后我跟着你的第二个样本,将linq与linq中的实体分开,并使用了tostring() 在一个句子中写所有我不能使用字符串,实体不支持它。

我仍然想知道我得到的结果洗牌的逻辑,是可怕的和不合逻辑的

请快速回答。