0

所以我是代码新手,我有一个已经完成并且无法更改的数据库,当我在控制器中调用客户端时出现此错误,因为它会查找不存在的 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; }
    }
4

1 回答 1

0

您必须告诉 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; }
}
于 2012-07-11T13:45:43.407 回答