Reputation: 9362
With the following code, I search for a specific Matrix in my repository and then assign it to Shuttle property.
var requestRepository = unitOfWork.Create<Request>();
var matrixRepository = unitOfWork.Create<Matrix>();
...
var matrix = matrixRepository.Find(m => m.MatrixID == matrixID).FirstOrDefault();
request.Shuttle = matrix;
....
This works. I try another alternative. With the following code, I prepare a Matrix object and try to attach it to my repository.
var requestRepository = unitOfWork.Create<Request>();
var matrixRepository = unitOfWork.Create<Matrix>();
...
var matrix = new Matrix { MatrixID = matrixID };
matrixRepository.Attach(matrix);
request.Shuttle = matrix;
....
This don't work. On the attach statement, I got the error: object with the same key already exists in the ObjectStateManager
Does someone can explain me?
Thanks.
Upvotes: 0
Views: 205
Reputation: 2760
At first way, you just find element and put it into matrix. But in second way you try to add matrix which can be already exists in matrixRepository.
EDIT
var matrix = matrixRepository.Find(m => m.MatrixID == matrixID).FirstOrDefault();
this show you that matrixID can be in matrixRepository if not return default.
but here
var matrix = new Matrix { MatrixID = matrixID };
matrixRepository.Attach(matrix); //if matrixRepository allready have matrix with matrixID you will get error
you just add it to matrixRepository
Upvotes: 1