为什么导航 属性 总是返回 null,即使数据存在?

Why navigation property is always returning null even if the data exists?

我很纠结这个,我在两个模型之间有一对多的关系(POS_citiesPOS_company

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; }
}

因此,我使用 Entity framework 构建了上面的代码,但它没有按预期生成代码,因此,我不得不根据需要修改代码,例如下面的 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 returns null :

现在,让我们确保数据确实存在于数据库中:

POS_cities

中的数据

POS_company

中的数据

那么,我做错了什么?为什么即使数据存在于数据库中,导航 属性 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]"

试试这个:

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; }

}