实体框架5递归关系

时间:2013-02-26 09:37:36

标签: entity-framework parent-child

CREATE TABLE ConfigurationItem
(  
  OID BIGINT NOT NULL
  ,ParentItemOID BIGINT 
);

ALTER TABLE ConfigurationItem ADD CONSTRAINT PK_CONFIGURATIONITEM PRIMARY KEY (OID);

ALTER TABLE ConfigurationItem ADD CONSTRAINT FK_CONFIGURATIONITEM_PARENTITEMOID FOREIGN KEY (ParentItemOID ) REFERENCES CONFIGURATIONITEM(OID);

每次获取数据ConfigurationItem我想得到 父ConfigurationItem 和子ConfigurationItems的列表 并且没有递归。

这是创建的实体

[Table("ConfigurationItem", Schema = "dbo")]
public partial class ConfigurationItem : TaggableItem
{
  public Int64 OID { get; set; }
  public Int64? ParentItemOID { get; set; }

  [ForeignKey("ParentItemOID")]
  public ConfigurationItem Parent;

  [InverseProperty("ParentItemOID")]
  //Not a virtual because it is need to be marshalled via WCF
  public List<ConfigurationItem> Children { get; set; } 
}

我无法使其发挥作用。

发生以下错误的示例:

InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=Invalid column name 'ConfigurationItem_OID'.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=32
Number=207
Procedure=""
Server=localhost
State=1

在Entity框架中使用它的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

我认为您的原始异常源于EF使用的默认命名约定。将ConfigurationItem类中的OID属性重命名为Configuration_OID,或者使用OID属性上的列注释来指示您要覆盖该列的默认命名约定,例如: [柱( “OID”)。

我有一个带有这样的自引用表的模式,我没有发现有必要使用InverseProperty注释,所以你可以摆脱它。