Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Fetch Data from database using Entity Framework 6

I have build a query to return data from two tables in which they are joined by inner join. Although, as the query seems fine, i am getting error message when i try to access the selected field names from the query. How do i use .SingleOrDefault() function in this query. Can anybody help me how should i proceed.

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"

            }

        }
    }

Thanks in advance.

like image 585
Jaan Avatar asked Nov 25 '13 17:11

Jaan


1 Answers

Try this:

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;                        
        }
    }
like image 129
Jurgen Vandw Avatar answered Nov 15 '22 03:11

Jurgen Vandw