2012-01-25 61 views
30

我得到:错误:无效的列名'OrganizationStructure_ID'。实体框架:无效的列名'OrganizationStructure_ID'

public OrganizationStructure() 
    { 
     ChildrenItems = new HashSet<OrganizationStructure>(); 
     InputDate = DateTime.Now; 
    } 

    public int ID { get; set; } 
    public string Name { get; set; } 

    public virtual int? ParentID { get; set; } 
    public int OrganizationID { get; set; } 
    public int OrganizationTypeID { get; set; } 
    public int OrganizationActivityID { get; set; } 
    public int OrganizationLocationID { get; set; } 

    public string AddRemark { get; set; } 
    public int UserId { get; set; } 
    public DateTime InputDate { get; set; } 
    public int? RemAttr { get; set; } 

    public virtual ICollection<OrganizationStructure> ChildrenItems { get; set; } 

index动作:

return View(_organizationStructureRepository.GetAll().ToList() 
      .Where(t => t.ParentID == null)); 
+0

是'OrganizationStructure'一个实体(来自EF?)你有什么例外? – gideon

+1

EF,例外:无效的列名称'OrganizationStructure_ID' –

+2

显然自动外键在某个时刻从{实体} ID更改为{实体} _ID。 EF5也许。 –

回答

37

那是因为你没有用的导航属性对您的FK财产。我预计ParentID应该指向父母OrganizationStructureChildrenItems应指向子女OranizationStructures

如果模型没有包含Parent导航属性于母公司OrganizationStructure必须使用流畅的API来告诉EF这ParentID是FK:

modelBuilder.Entity<OrganizationStructure>() 
      .HasMany(o => o.ChildrenItems) 
      .WithOptional() 
      .HasForeignKey(c => c.ParentID); 
+3

一个人把这个代码放在哪里? –

+3

@boomhauer:在派生的'DbContext'类中覆盖'OnModelCreating'方法并放置所有映射。另一种选择是使用'EntityTypeConfiguration'派生类并将其注册到'OnModelCreating'中。 –

+0

我发现如何添加一个foreignkey attibute来为我照顾这个模型。但是谢谢 –

3

我已经想通了,是当你有一个ICollection的那引用一个表并且没有可以找出的列,它会为您创建一个表来试图建立连接。这种情况发生在ICollection上,并促使我“蝙蝠”试图找出答案。

3

我有一个类似的问题,删除不需要的公共虚拟ICollection的条目,解决了它。

+0

你达人......在最后的60分钟里窃听我 – Tosh

+0

同样在这里,直到我找到这个 – stillsmallvoice

1

这也可能是如果你在子实体中声明引用域为简单字段,但不是属性!

int ParentId //will be ignored; 

int ParentId {get; set;} // it'ok (but could be ignored 
         //if the parent entity name isn't 'Parent'); 

[ForeignKey("MyParentEntity")] 
int ParentId {get; set;} // is the best way (or use fluent-api) 
相关问题