实体框架代码第一:如何为这种关系创建一对多?

时间:2012-07-11 13:42:40

标签: c# asp.net-mvc-3 entity-framework ef-code-first

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

1 个答案:

答案 0 :(得分:0)

您必须告诉EF empresa是导航属性Empresa的外键,否则它将采用默认外键名称,即“NavigationPropertyName + UnderScore + KeyNameInTargetClass”= {{1 }}。您可以通过应用Empresa_id属性来覆盖此默认值:

[ForeignKey]