我已经构建了一个查询来从两个表中返回数据,在这两个表中,内联接将它们连接起来。虽然,因为查询似乎很好,当我尝试从查询中访问选定的字段名称时,我收到错误消息。我如何在此查询中使用.SingleOrDefault()函数。任何人都可以帮助我如何继续。
private void FindByPincode(int iPincode)
{
using (ABCEntities ctx = new ABCEntities())
{
var query = from c in ctx.Cities
join s in ctx.States
on c.StateId equals s.StateId
where c.Pincode == iPincode
select new {
s.StateName,
c.CityName,
c.Area};
// var query = ctx.Cities.AsNoTracking().SingleOrDefault(_city => _city.Pincode == iPincode);
if (query != null)
{
cboState.SelectedItem.Text =query.State; //Getting error "Could not found"
cboCity.SelectedItem.Text = query.CityName; //Getting error "Could not found"
txtArea.Text = query.Area; //Getting error "Could not found"
}
}
}
提前致谢。
答案 0 :(得分:7)
试试这个:
using (ABCEntities ctx = new ABCEntities())
{
var query = (from c in ctx.Cities
join s in ctx.States
on c.StateId equals s.StateId
where c.Pincode == iPincode
select new {
s.StateName,
c.CityName,
c.Area}).First().SingleOrDefault();
if (query != null)
{
cboState.SelectedItem.Text =query.State;
cboCity.SelectedItem.Text = query.CityName;
txtArea.Text = query.Area;
}
}
答案 1 :(得分:0)
是否可以选择名为StateName的字段,然后选择状态。
cboState.SelectedItem.Text =query.State;
cboState.SelectedItem.Text =query.StateName;
请提供有关错误和代码类结构的更多详细信息
答案 2 :(得分:0)
以下是类似情况对我的影响:
using (ABCEntities ctx = new ABCEntities())
{
var query = (from c in ctx.Cities
join s in ctx.States
on c.StateId equals s.StateId
where c.Pincode == iPincode
select new {
s.StateName,
c.CityName,
c.Area}).Single();
if (query.Any())
{
cboState.SelectedItem.Text =query.State;
cboCity.SelectedItem.Text = query.CityName;
txtArea.Text = query.Area;
}
}
请注意,我在那里使用了query.Any(),这是因为query!= null将始终返回true。但是any()检查查询是否返回了1个或多个记录,如果是,Any()返回true,如果查询没有返回任何记录,则Any()返回false。