我厉害卡在这一块,我有一到两款车型(POS_cities
,POS_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即使数据出现在数据库:
现在,让我们确保数据是实际存在于数据库:
在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]"
由于您使用的相当不寻常的命名惯例,很可能需要显式地映射了'cities'和' CityID'属性(具有'ForeignKey'属性或流利的API)。 –
@IvanStoev,感谢您的回复,我已经通过sql server中的表定义了这一点,所以外键关系在那里似乎没问题,仍然需要明确定义'[ForeignKey]'? –
数据库是一件事,实体模型 - 另一个。这就是为什么它被称为O(bject)R(elational)M(apping)。如果你没有指定正确的映射,EF会做谁知道什么:)让我们做一个测试,看看发生了什么。如果你使用'var sql = db.POS_company.Include(p => p.cities).ToString();','sql'变量包含什么? –