Linq 查询不返回值
本文关键字:返回值 查询 Linq | 更新日期: 2023-09-27 18:30:42
- 框架:.Net 4.5
我正在用数据库中的数据填充文本框字段。但是,调试后,我发现我的 Linq 查询没有返回值。
protected void btnChoose_Click(object sender, EventArgs e)
{
API_DatabaseEntities1 db = new API_DatabaseEntities1();
if (ddlCustomer.SelectedValue == "Marisol") {
tbDescription.Text = (from c in db.Customers
where c.CustomerID == 4
select c.ProductDescription).ToString();
tbFName.Text = (from c in db.Customers
where c.CustomerID == 4
select c.Fname).ToString();
tbSocial.Text = (from c in db.Customers
where c.CustomerID == 4
select c.SSN).ToString();
tbDOB.Text = (from c in db.Customers
where c.CustomerID == 4
select c.DOB).ToString();
tbFName1.Text = (from c in db.Customers
where c.CustomerID == 4
select c.Fname).ToString();
tbMName.Text = (from c in db.Customers
where c.CustomerID == 4
select c.Mname).ToString();
tbLName.Text = (from c in db.Customers
where c.CustomerID == 4
select c.Lname).ToString();
tbPrimaryPhone.Text = (from c in db.Customers
where c.CustomerID == 4
select c.PrimaryPhone).ToString();
tbSecondaryPhone.Text = (from c in db.Customers
where c.CustomerID == 4
select c.SecondaryPhone).ToString();
tbAdd1.Text = (from c in db.Customers
where c.CustomerID == 4
select c.Address).ToString();
tbCity.Text = (from c in db.Customers
where c.CustomerID == 4
select c.City).ToString();
tbZip.Text = (from c in db.Customers
where c.CustomerID == 4
select c.Zip).ToString();
tbEmail.Text = (from c in db.Customers
where c.CustomerID == 4
select c.Email).ToString();
tbMonLease.Text = (from c in db.Customers
where c.CustomerID == 4
select c.MortLeaseAmt).ToString();
tbEmployer.Text = (from c in db.Customers
where c.CustomerID == 4
select c.Employer).ToString();
tbPosition.Text = (from c in db.Customers
where c.CustomerID == 4
select c.Position).ToString();
tbHireDate.Text = (from c in db.Customers
where c.CustomerID == 4
select c.Position).ToString();
tbWorkPhone.Text = (from c in db.Customers
where c.CustomerID == 4
select c.WorkPhone).ToString();
tbGross.Text = (from c in db.Customers
where c.CustomerID == 4
select c.GrossIncome).ToString();
}
Debug.WriteLine(tbGross.Text);
}
此时,我不确定我的数据库连接或 Linq 查询是否存在问题。感谢您提供的任何帮助。
我想你的意思是得到一个客户而不是一个列表。
select
将返回一个集合而不是一个项目,请像这样更改它:
var customer = (from c in db.Customers
where c.CustomerID == 4
select c).FirstOrDefault();
请注意 FirstOrDefault()
的调用,这将返回 1 个客户,而不是包含 1 个客户的列表。
如果查询未返回任何内容,FirstOrDefault()
将返回null
:
if(customer == null)
return; // no customer found
然后,您可以像这样填充文本字段:
tbDescription.Text = customer.ProductDescription;
tbFName.Text = customer.Fname;
etc.
请这样做:
var oneRec = (from c in db.Customer
where c.CustomerID == 4
select c).FirstOrDefault();
tbDescription.Text = oneRec.ProductDescription;
tbFName.Text = oneRec.Fname;
tbSocial.Text = oneRec.SSN;
// ect