Linq和c#,跳过记录,类型转换错误



我试图跳过并从查询中获取,但得到casting错误:

Error   1   Cannot implicitly convert type 'System.Linq.IQueryable<tblComment>' to 'System.Linq.IOrderedQueryable<tblComment>'. An explicit conversion exists (are you missing a cast?)
Error   2   Cannot implicitly convert type 'System.Linq.IQueryable<tblComment>' to 'System.Linq.IOrderedQueryable<tblComment>'. An explicit conversion exists (are you missing a cast?)

行:

if(ToSkip > 0)
    q = q.Skip(ToSkip);
if(ToTake > 0)
    q = q.Take(ToTake);

这是完整的方法,任何帮助是感激的!我所要做的就是过滤返回的记录,如果它们被指定这样做的话。

另外,这是一个很好的方法,还是数据库每次都会返回所有的记录?也就是说,它会获取所有的记录,然后做跳跃和取吗?我想让它更有效率。

/// <summary>
/// Fetches all comments from a category
/// </summary>
/// <param name="Category">Category ID of comments to fetch</param>
/// <param name="Identifier">Identifier ID for category</param>
/// <param name="ToTake">How many to take in query. 0 = all</param>
/// <param name="ToSkip">How many to skip.</param>
/// <returns></returns>
public static Comment[] FetchCommentsByNewest(int Category, int Identifier, int ToSkip, int ToTake)
{
    Comment[] Comments = new Comment[1];
    using (DataClassesDataContext db = new DataClassesDataContext())
    {
        // Loop each comment and insert newest first to array
        var q = (from c in db.tblComments where c.CategoryID == Category && c.IdentifierID == Identifier orderby c.PostDate descending select c);
        if(ToSkip > 0)
            q = q.Skip(ToSkip);
        if(ToTake > 0)
            q = q.Take(ToTake);
        Comments = new Comment[q.Count()];
        int i = 0;
        foreach (var Rec in q)
        {
            i++;
        }
    }
    return Comments;
}

您总是可以通过将代码更改为以下代码来绕过它:

var q = (
   from c in db.tblComments 
   where c.CategoryID == Category && c.IdentifierID == Identifier 
   orderby c.PostDate descending select c
)
.Skip(ToSkip > 0 ? ToSkip : 0)
.Take(ToTake > 0 ? ToTake : int.MaxValue);

使用与ChrisF显示的相同的逻辑并使用return q.ToArray()完成语句,或者如果您需要一个模型类,例如Comment然后使用AutoMapper http://automapper.codeplex.com/

return q.select( x=>  new Comment{Name = x.Name, Description = x.Description}).ToArray();

注意: ToArray或ToList()将导致查询被执行。

相关内容

  • 没有找到相关文章

最新更新