【问题标题】:Search if exist before insert in Linq DB in C# for WP8在 C# for WP8 中插入 Linq DB 之前搜索是否存在
【发布时间】:2014-07-30 16:52:53
【问题描述】:

我正在开发一个 WP8 问题应用程序,该应用程序将数据发送到数据库,但会跳过现有数据。 我有一个名为“DBHelper.cs”的类,它包含

public static void InsertQuestion(Question oQuestion)
{
    using (var context = new QuestionContext(ConnectionString))
    {
        if(context.DatabaseExists())
        {
            Question oQuestionWord = (from ostd in context.Questions where ostd.Word == oQuestion.Word select ostd).Single();
            if (oQuestionWord.Word == null)
            {
                context.Questions.InsertOnSubmit(oQuestion);
                context.SubmitChanges();
            }
        }
    }
}

而mainpage.xaml.cs中的这段代码

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    Question oQuestion = new Question();
    oQuestion.Word = "One";
    DBHelper.InsertQuestion(oQuestion);``
    oQuestion = new Question();
    oQuestion.Word = "Two";
    DBHelper.InsertQuestion(oQuestion);
    oQuestion = new Question();
    oQuestion.Word = "One";
    DBHelper.InsertQuestion(oQuestion);
    base.OnNavigatedTo(e);
}

构建解决方案时没有错误,但启动应用时崩溃。

【问题讨论】:

    标签: c# linq windows-phone-8


    【解决方案1】:

    我认为错误的原因是Single 方法。 Single 如果找到多条记录,则会引发异常。尝试改用FirstOrDefault

    var oQuestionWord = context.Questions.FirstOrDefault(q => q.Word == oQuestion.Word);
    if (oQuestionWord != null && oQuestionWord.Word == null)
    {
        context.Questions.InsertOnSubmit(oQuestion);
        context.SubmitChanges();
    }
    

    您可能没有收到有用的异常消息,因为它发生在OnNavigatedTo 事件中。您可能想看看this question...

    【讨论】:

    • 这段代码完美运行,只需将“(oQuestionWord != null && oQuestionWord.Word == null)”编辑为“(oQuestionWord == null)”,谢谢! :D
    猜你喜欢
    • 1970-01-01
    • 2015-05-27
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多