繁体   English   中英

如何使用 Entity Framework 6 从数据库中获取数据

[英]How to Fetch Data from database using Entity Framework 6

我已经构建了一个查询来从两个表中返回数据,其中它们通过内部联接连接。 虽然,由于查询看起来不错,但当我尝试从查询访问选定的字段名称时收到错误消息。 我如何在此查询中使用 .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;                        
        }
    }

可能是您正在选择一个名为StateName的字段,然后访问State。

 cboState.SelectedItem.Text =query.State;    



cboState.SelectedItem.Text =query.StateName;    

请提供有关错误和代码类结构的更多详细信息

以下是类似情况对我的影响:

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM