Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple added entities may have the same primary key in Entity Framework

I am working in a project using EF 4.0.

The Employee table has a column ReferEmployeeID which contains the employee id of the employee that is referring a new employee in the system. So Employee is a self-referencing table.

Now in the case of an employee who is not added to the system is about to add and he also refers another employee in the system, the row should be added altogether.

ActualEmployee save not called yet and then ReferEmployee.Employee = ActualEmployee

I understand the issue is that both the employees actual and refer has Employee ID set to 0, but how to come around this problem.

like image 610
manav inder Avatar asked Dec 16 '11 06:12

manav inder


People also ask

Can there be 2 primary keys in a ER diagram?

I understand that a primary key is a column that uniquely identifies every row in a database table. Therefore you can have only one primary key in your entity.

Is it possible for an entity to not have a primary key?

Every entity in the data model shall have a primary key whose values uniquely identify entity instances. The primary key attribute cannot be optional (i.e., have null values).


1 Answers

Assuming that the EmployeeID in your database table is defined as INT IDENTITY, then you could do this:

// create two new employees - one refers to the other
Employee john = new Employee { EmployeeID = -1, EmpName = "John" };
Employee peter = new Employee { EmployeeID = -2, EmpName = "Peter", ReferEmployeeID = -1 };

// add them to the EF model
ctx.AddToEmployees(john);
ctx.AddToEmployees(peter);

// save changes
ctx.SaveChanges();

So basically, define your new employees with "dummy" EmployeeID values and establish the link (Peter references John here, by means of its "dummy" ID).

When saving this into SQL Server, the Entity Framework will handle the process of getting the real EmployeeID values (which SQL Server hands out when inserting the row) and EF will maintain that link between the two employees.

like image 112
marc_s Avatar answered Sep 17 '22 17:09

marc_s