1

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!

1
  • Well, I have large tree structure. When I add the base element (for example entities.AddToShop(shop)) and after that I save changes all the data goes to the database, and all employees are saved there (it doesn't matter if they already exists). I want to save just the unique employees. Commented May 19, 2012 at 8:49

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Tried this but i get this error: "The object could not be added to the EntityCollection or EntityReference. An object that is attached to an ObjectContext cannot be added to an EntityCollection or EntityReference that is not associated with a source object."
I think this is an issue with multiple dbcontexts. Try performing all the work with a single dbcontext object (I usually wrap the codeblock within a using statement).
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.