2017-07-26 50 views
0

我厲害卡在這一塊,我有一到兩款車型(POS_citiesPOS_company)之間有許多關係爲什麼導航屬性總是返回null,即使數據存在?

POS_cities.cs

public class POS_cities 
{   
    [Key] 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public int CountryID { get; set; } 
    public virtual POS_country country { get; set; }     
    public virtual ICollection<POS_company> company { get; set; } 
} 

POS_company.cs

public class POS_company 
{   
    [Key] 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public string BusinessName { get; set; } 
    public int CityID { get; set; } 
    public virtual POS_cities cities { get; set; } 
} 

因此,我使用實體框架搭建上面的腳本,但它沒有按預期生成代碼,s O,我不得不根據我的需要修改代碼,如下面的Index行動:

public ActionResult Index() 
{ 
    var pOS_company = db.POS_company.Include(p => p.cities);  
    return View(pOS_company.ToList()); 
} 

在上面的代碼EF沒有產生Include(p => p.cities)功能,所以,我不得不添加明確。現在,當我執行上述Index()動作,導航屬性cities返回null即使數據出現在數據庫:

enter image description here

現在,讓我們確保數據是實際存在於數據庫:

在POS_cities數據

enter image description here

數據在POS_company

enter image description here

那麼,什麼可能是我做錯了事情?爲什麼導航屬性cities即使數據存在於數據庫中也會返回null?感謝提前:)

更新

"SELECT [Extent1].[ID] AS [ID], [Extent1].[Name] AS [Name], [Extent1].[BusinessName] AS [BusinessName], [Extent1].[CityID] AS [CityID], [Extent2].[ID] AS [ID1], [Extent2].[Name] AS [Name1], [Extent2].[CountryID] AS [CountryID] FROM [dbo].[POS_company] AS [Extent1] LEFT OUTER JOIN [dbo].[POS_cities] AS [Extent2] ON [Extent1].[CityID1] = [Extent2].[ID]" 
+0

由於您使用的相當不尋常的命名慣例,很可能需要顯式地映射了'cities'和' CityID'屬性(具有'ForeignKey'屬性或流利的API)。 –

+0

@IvanStoev,感謝您的回覆,我已經通過sql server中的表定義了這一點,所以外鍵關係在那裏似乎沒問題,仍然需要明確定義'[ForeignKey]'? –

+0

數據庫是一件事,實體模型 - 另一個。這就是爲什麼它被稱爲O(bject)R(elational)M(apping)。如果你沒有指定正確的映射,EF會做誰知道什麼:)讓我們做一個測試,看看發生了什麼。如果你使用'var sql = db.POS_company.Include(p => p.cities).ToString();','sql'變量包含什麼? –

回答

0

試試這個:

public class POS_company 
{   
    [Key] 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public string BusinessName { get; set; } 

    [ForeignKey("CityID")] 
    public virtual POS_cities cities { get; set; } 
    public int CityID { get; set; } 

} 
+0

正如伊萬所建議的那樣,EF有時會生成自己的名稱,這些名稱在模型類中沒有定義。在我的情況下,生成名爲CityID1的列,我知道它不存在於數據庫中,因此當它查詢列名「CityID1」時,它返回null,所以我必須顯式定義'[ForeignKey( 「CityID」)]'屬性。 –

相關問題