Silverlight异常中的LINQ to SQL [英] LINQ to SQL in silverlight exception
问题描述
This is a continution of my previous question: Could not find an implementation of the query pattern
现在,我设法查询数据库,但似乎无法在网页上获取内容.
Now I managed to query my database I can't seem to get the content on my webpage.
我尝试使用以下代码返回代码:
I try to return the code using the following code:
private void button1_Click(object sender, RoutedEventArgs e)
{
Service1Client client = new Service1Client();
client.GetPersoonByIDCompleted += new EventHandler<GetPersoonByIDCompletedEventArgs>(client_GetPersoonByIDCompleted);
client.GetPersoonByIDAsync("1");
}
void client_GetPersoonByIDCompleted(object sender, GetPersoonByIDCompletedEventArgs e)
{
if (e.Error != null)
textBox1.Text = e.Error.ToString();
else
label1.Content = e.Result.Voornaam.ToString();
}
但是,当我按下按钮时,出现以下错误:
However when I press the button I get the following errors:
对象引用未设置为对象的实例.
Object reference not set to an instance of an object.
在 SilverlightApplication1.MainPage.client_GetPersoonByIDCompleted(Object 发送者,GetPersoonByIDCompletedEventArgs e)位于 SilverlightApplication1.ServiceReference1.Service1Client.OnGetPersoonByIDCompleted(Object 状态)
at SilverlightApplication1.MainPage.client_GetPersoonByIDCompleted(Object sender, GetPersoonByIDCompletedEventArgs e) at SilverlightApplication1.ServiceReference1.Service1Client.OnGetPersoonByIDCompleted(Object state)
奇怪的是,当我不使用LINQ而是使用普通的SQL时,它可以正常工作.
The weird thing is it works when I do not use LINQ, but normal SQL.
string sql = "SELECT ID, naam, voornaam, leeftijd FROM tblPersoon WHERE id=@pmID";
Persoon pers = null;
string connstr = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connstr))
{
SqlCommand com = new SqlCommand(sql, cn);
com.Parameters.AddWithValue("pmID", id);
cn.Open();
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
pers = new Persoon();
pers.ID = reader.GetString(0);
pers.Naam = reader.GetString(1);
pers.Voornaam = reader.GetString(2);
pers.Leeftijd = reader.GetInt32(3);
}
}
return pers;
}
LINQ结果:
SQL结果:
感谢您的帮助,我非常感谢! 托马斯
Thank you for helping me, I grealy appreciate it! Thomas
推荐答案
通过在无效的情况下尝试引用"e.Result"属性(即,当方法调用返回异常而不是a)时,获得该特定异常.价值.在引用e.Result之前,请确认e.Error == null,如果没有,请沉迷于一些错误处理或消息传递代码,例如:
You get that particular exception by trying to reference the "e.Result" property when it's not valid, i.e., when the method call returned an exception instead of a value. Before you reference e.Result, confirm that e.Error == null, and if it doesn't, indulge yourself in some error handling or messaging code, e.g.:
void client_GetPersoonByIDCompleted(object sender, GetPersoonByIDCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("An error occurred: " + e.Error.ToString());
}
else
{
label1.Content = e.Result;
}
}
或类似的东西.
这篇关于Silverlight异常中的LINQ to SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!