Closed JanKupke1 closed 4 years ago
Thank you for taking the time to add your code.
The problem is that you have is because you are trying to create a entity with relationships. What was happening was it was creating NEW HasTwoNormalEntity
(which you wanted) and NEW NormalEntity
(which I'm sure isn't what you wanted). You then got an exception because the NormalEntityDto
had the Id
of the NormalEntity
in the database so when it tried to add a new NormalEntity
with the same key then it throw the exception.
So, one good solution (there are others) is to use the NormalEntity
in your HasTwoNormalEntityDto
instead of NormalEntityDto
and assign the tracked version from the NormalEntity
to the two navigational properties. Here is the fixed code.
Note I also took out the NormalEntity1/2Id
out too. You have either the the navigational property OR the foreign keys, but not both.
public class HasTwoNormalEntityDto : ILinkToEntity<HasTwoNormalEntity>
{
public int Id { get; set; }
public NormalEntity NormalEntity1 { get; set; }
public NormalEntity NormalEntity2 { get; set; }
}
[Fact]
public void ServiceCreateAndSave_SaveANewItemThatContainsTwoReferencesToAnExistingItem_ThrowsExeption()
{
//... other parts of the test same as before
//ATTEMPT
var fistNormal = context.NormalEntities.First(); //In my Case selected by a Combobox
HasTwoNormalEntityDto hasTwoNormalEntityDto = new HasTwoNormalEntityDto();
hasTwoNormalEntityDto.NormalEntity1 = fistNormal;
hasTwoNormalEntityDto.NormalEntity2 = fistNormal;
//.... no exception
}
}
Couple of things to say at the end:
Good afternoon,
I have a problem using your service. The problem is that automapper always creates a new instance of an object, i.e. it makes two instances of one object.
I have done a lot of internet research, but I can't get to the point where it works for me.
As a summary, one can say that in the service: entity = _mapper.Map(studentclass);
is used, but it should be _mapper.Map(studentclass, entity);.
But to implement this cleverly I did not manage to do so far. It would be really great if you had a hint for me.
Thanks for your efforts: Jan Kupke
I tried to overwrite the update method in the context class with the following code, but this did not lead to a solution:
Also I have found a class to address this problem, but I haven't found a way to integrate it into the service.