实体框架5 .net 4 - 数据库第一个自引用实体

时间:2012-12-19 01:13:15

标签: entity-framework

尝试完成与http://www.codeproject.com/Articles/206410/How-to-Configure-a-Self-Referencing-Entity-in-Code类似的操作,但在我的情况下,我不首先使用代码而不是db。 我收到此错误{“违反PRIMARY KEY约束'pk_employee'。无法在对象'dbo.Employee'中插入重复键。\ r \ n语句已终止。”}。

        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; }

}

1 个答案:

答案 0 :(得分: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();