[英]Entity Framework Code First: How can I create a One-to-Many for this relationships?
所以我是代碼firt的新手,我有一個已經完成並且無法更改的數據庫,當我在控制器中調用客戶端時收到此錯誤,因為出現此錯誤是因為它查找不存在的Empresa_id,所以我可以告訴尋找正確的領域?
return View(clientes.ToPagedList(pageNumber, pageSize));
it return this select
SELECT
[Extent1].[id] AS [id],
[Extent1].[name] AS [name],
[Extent1].[empresa] AS [empresa],
[Extent1].[Empresa_id] AS [Empresa_id]
FROM [dbo].[cliente] AS [Extent1]
ORDER BY [Extent1].[name] ASC}
public class cliente
{
[Key]
public int id { get; set; }
public string name { get; set; }
public int empresa { get; set; } // foreing key
public virtual empresa Empresa { get; set; }
}
public class empresa
{
[Key]
public int id { get; set; }
public string descripcion { get; set; }
public virtual ICollection<cliente> Clientes { get; set; }
}
您必須告訴EF empresa
是導航屬性Empresa
的外鍵,否則它將采用默認的外鍵名稱,即“ NavigationPropertyName + UnderScore + KeyNameInTargetClass” = Empresa_id
。 您可以通過應用[ForeignKey]
屬性覆蓋此默認設置:
public class cliente
{
[Key]
public int id { get; set; }
public string name { get; set; }
[ForeignKey("Empresa")]
public int empresa { get; set; }
public virtual empresa Empresa { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.