Reputation:
I have to following problem. I've large collection of XML files. In each XML file there are different employees. I have to add the unique employees to the database. In the database each employee has first name, last name and birth date. I want to check whether employee with the same properties already exists in the database and if it doesn't to insert it.
I'm using the following code:
Entities entities;
entities.AddToEmployee(emp);
entities.SaveChanges();
My employee is connected with another data structure - sales. So I need to add just the employee's primary key to the sales table but not the whole employee in the database (in case that it already exists).
Thanks in advance!
Upvotes: 1
Views: 1779
Reputation: 1936
In the Entity Framework, you can create and modify relationships in several ways. In your case I would first search for an employee and if it exists I would just set the ForeingKey instead of navigation property like this
sale.EmployeeID = x; // id of existing employee
if employee is new you have to create a new employee-object, then reference it from sale object and then save it.
If you are recieving "...An object that is attached to an ObjectContext cannot be added to an EntityCollection..." error please make sure you have only one context opened. I prefer to wrap all my db operations like this
using(var dbContext = new MyContext())
{
//do persistence stuff
}
Upvotes: 0
Reputation: 5247
The 'Find or Add Pattern' can be useful in these types of circumstance:
var db = new YourContext();
var emp = db.Employees.Find(empID) ?? db.Employees.Add( new Employee { FirstName ="xx" , LastName="xxx"});
db.SaveChanges();
This way the emp object has been loaded if it exists in the database or created and saved to the database. You might need to replace the Find() with a Where() if you are searching on multiple properties.
Upvotes: 1