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

标签 c# entity-framework entity-framework-4 linq-to-entities

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

相关文章:

c# - 工厂和 C#

c# - 如何读取owin中间件中的自定义 header ?

c# - 带有 TransactionScope 的 EF6 - IsolationLevel.ReadUncommitted 但首先获得 ReadCommitted

c# - 自创建数据库以来,支持 'EmployeeDetailsContext' 上下文的模型已发生更改。

C# 自动转换接口(interface)方法

entity-framework - 如何访问EF中多表中的数据?

c# - Entity Framework : Multiple Where Statements Execution Plan

c# - 如何创建具有 EntityState 未知关系的对象

linq-to-sql - 从LINQ到SQL到Entity Framework 4.0的迁移-技巧,文档等

oracle - 使用 EF4 将 Int32 转换为 Oracle number(5)