2012-12-19 72 views
3

試圖完成類似於http://www.codeproject.com/Articles/206410/How-to-Configure-a-Self-Referencing-Entity-in-Code的事情,但在我的情況下,我並沒有先使用代碼,而是先使用db。 我得到這個錯誤{「違反PRIMARY KEY約束'pk_employee'。不能在對象'dbo.Employee'中插入重複鍵。\ r \ n該語句已被終止。」}。實體框架5 .net 4 - 數據庫第一個自我引用實體

 EmployeeEntity employeeEntity = null; 
     EmployeeEntity employeeDelegate = null; 

      // already EXISTS in table 
      employeeDelegate = new EmployeeEntity 
      { 
       EMPL_UNO = 1, 
       FULLNAME = "manager, name" 
      }; 


     employeeEntity = new EmployeeEntity 
     { 
      EMPL_UNO = 2, 
      FULLNAME = "employee, name", 
      DELEGATE_EMPL_UNO = 1, 
      Delegate = employeeDelegate 
     }; 



MyContext.EmployeeEntities.Add(Employee); 
    // throws error 
MyContext.SaveChanges(); 

//表

CREATE TABLE [dbo].[Employee](
    [EMPL_UNO] [int] NOT NULL, 
    [FULLNAME] [varchar](255) NULL, 
    [DELEGATE_EMPL_UNO] [int] NULL, 
CONSTRAINT [pk_employee] PRIMARY KEY CLUSTERED 
(
    [EMPL_UNO] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

GO 

SET ANSI_PADDING OFF 
GO 

ALTER TABLE [dbo].[Employee] WITH CHECK ADD CONSTRAINT [FK_Employee_Delegate] FOREIGN KEY([DELEGATE_EMPL_UNO]) 
REFERENCES [dbo].[Employee] ([EMPL_UNO]) 
GO 

ALTER TABLE [dbo].[Employee] CHECK CONSTRAINT [FK_Employee_Delegate] 
GO 

//實體

public partial class EmployeeEntity 
{ 
    public EmployeeEntity() 
    { 
     this.SubOrdinates = new HashSet<EmployeeEntity>(); 
    } 

    public int EMPL_UNO { get; set; } 
    public string FULLNAME { get; set; } 
    public Nullable<int> DELEGATE_EMPL_UNO { get; set; } 

    public virtual ICollection<EmployeeEntity> SubOrdinates { get; set; } 
    public virtual EmployeeEntity Delegate { get; set; } 

} 
+0

會不會包括在對象中的對象的引用消除使其有POCO的目的是什麼? –

回答

3

您的代碼會失敗,因爲Add方法將插入從對象圖,並在你的情況下,兩個新的和現有的所有未知的實體員工對EF環境未知,因爲您沒有告知上下文有關第一個實體的存在(設置ID不夠)。比如,你可以使用:

var employeeDelegate = new EmployeeEntity { 
    EMPL_UNO = 1, 
    FULLNAME = "manager, name" 
}; 

MyContext.EmployeeEntities.Attach(employeeDelegate); 

var employeeEntity = new EmployeeEntity { 
    EMPL_UNO = 2, 
    FULLNAME = "employee, name", 
    DELEGATE_EMPL_UNO = 1, 
    Delegate = employeeDelegate 
}; 


MyContext.EmployeeEntities.Add(Employee); 
MyContext.SaveChanges(); 

但你的具體情況這應該工作以及:

var employeeEntity = new EmployeeEntity { 
    EMPL_UNO = 2, 
    FULLNAME = "employee, name", 
    DELEGATE_EMPL_UNO = 1 // Just set the FK, you don't need a reference if you don't want to modify the delegate as well 
}; 

MyContext.EmployeeEntities.Add(Employee); 
MyContext.SaveChanges(); 
+0

感謝您的回覆我真的很感激它。經理和員工何時不存在?當我嘗試「附加」時,我得到一個「INSERT語句與FOREIGN KEY SAME TABLE CONSTRAINT衝突...」 – dm80

+0

如果經理不存在,您的以前的解決方案將工作。 –