How to Fetch Data from database using Entity Framework 6
c#, entity-framework, entity-framework-4, linq-to-entities
Solution
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;
}
}
Problem
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.