[英]Using Database first approach in Entity framework, how to fetch the data from a single table only which has multiple foreign key relationship?
[英]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.