2009-08-20 93 views
0

我有下面的代码,试图让用户通过单击WinForm上的Next或Previous来在数据库中“浏览”Case Notes。它只会抓住第一个案例笔记。 我在做什么错?使用LINQ to SQL实现Next/Previous使用LINQ to SQL

对这篇文章进行了大量修改,我很抱歉,但在遵循Jon Skeet的建议之后,我能够“修复”原本错误的内容,但仍然无法正常工作。

我是否需要重构我的查询以考虑当前注释?如果是这样,我该怎么做?

public static Guid NextCaseNoteID (int personID) 
    { 
     var context = new MatrixDataContext(); 

     Guid nextNoteID = (from caseNote in context.tblCaseNotes 
                where caseNote.PersonID == personID 
                orderby caseNote.InsertDate 
                select caseNote.CaseNoteID).Skip(1).FirstOrDefault(); 

     return nextNoteID; 
    } 


这是我结束了,感谢大家谁张贴,随后想起了生病想到火车...

看来,虽然我现在的工作很好试图证明,如果我需要跳过(1)仍然.... 谢谢!

以供将来参考

 public static Guid NextCaseNoteID (int personID, DateTime? insertDate) 
    { 
     var context = new MatrixDataContext(); 

     Guid nextNoteID = (from caseNote in context.tblCaseNotes 
                where caseNote.PersonID == personID && caseNote.InsertDate > insertDate 
                orderby caseNote.InsertDate 
                select caseNote.CaseNoteID).Skip(1).FirstOrDefault(); 

     return nextNoteID; 
    } 

    public static Guid PreviousCaseNoteID(int personID, DateTime? insertDate) 
    { 
     var context = new MatrixDataContext(); 

     Guid nextNoteID = (from caseNote in context.tblCaseNotes 
          where caseNote.PersonID == personID && caseNote.InsertDate < insertDate 
          orderby caseNote.InsertDate 
          select caseNote.CaseNoteID).Skip(1).FirstOrDefault(); 

     return nextNoteID; 
    } 
+0

你为什么要返回分辨率而不仅仅是guid? – Geoff 2009-08-20 19:17:18

+0

@Geoff:Resharper告诉我,我没有(没有)知道更好。在Jon Skeet的帖子下看到我的评论。 – 2009-08-20 19:19:52

+0

根据您的编辑,您是否可以确认caseNote.CaseNoteID返回的内容实际上是32位数,并且有4个破折号? – Geoff 2009-08-20 19:32:50

回答

2

好了,最明显的问题是,你正在创建一个匿名类型的实例。试试这个:

public static IQueryable<Guid> NextCaseNoteID (int personID) 
{ 
    var context = new MatrixDataContext(); 

    IQueryable<Guid> nextNoteID = (from caseNote in context.tblCaseNotes 
            where caseNote.PersonID == personID 
            orderby caseNote.InsertDate 
            select caseNote.CaseNoteID).Skip(1).Take(1); 

    return nextNoteID; 
} 

我不能肯定它确实是你以后,但它很可能至少编译...

你确定你不想回实际GUID而不是IQueryable<Guid>

你可能想打电话给FirstOrDefault(),而不是Take(1) ...

编辑:好的,所以它确实返回一个GUID ...你说这是不是工作,而是不如何它不工作。如果你想获取下一个案例笔记,你应该很可能传递案例笔记ID而不是个人ID,但它不是非常清楚...

+0

不,我想要实际的Guid,但我遇到了同样类型的问题,我不想用我在这方面的许多失败尝试来轰炸我的帖子。无论如何,我相信这就是Joel Splosky所建议的。 FirstOrDefault()会做什么,尽可能多的尝试和遍历....谢谢 – 2009-08-20 19:14:22

+0

其实,我刚刚意识到使用Guid是我最初尝试的,但它不会编译和'intelisense'(ReSharper ??)建议我将noteID的类型更改为IQueryable .... – 2009-08-20 19:17:33

+0

'FirstOrDefault'将执行查询并返回第一个结果*或*类型的默认值(即在这种情况下为'default(Guid)')。 – 2009-08-20 19:47:06

0

我可能听起来像个白痴。但是,为什么你不能使用datareader来做这件事(特别是当你使用linq to sql时,又会调用SQL Server来做到这一点)?

让我知道,如果我完全误解了这个问题。

1

如果想要下一个/上一个方法,你不应该通知现在的位置是什么吗? 然后跳过currentPosition + 1为next和currentPosition - 1.

我通常使用Single()而不是FirstOrDefault()。但我认为这没有什么区别。