我已经构建了一个查询以从两个表中返回数据,这两个表通过内部连接连接在一起。尽管查询看起来不错,但当我尝试从查询中访问选定的字段名称时收到错误消息。我如何在此查询中使用 .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"
}
}
}
提前致谢。
最佳答案
试试这个:
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}).FirstOrDefault();
if (query != null)
{
cboState.SelectedItem.Text =query.State;
cboCity.SelectedItem.Text = query.CityName;
txtArea.Text = query.Area;
}
}
关于c# - 如何使用 Entity Framework 6 从数据库中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20199727/