1

I have the following Map created:

Mapper.CreateMap<UsuarioViewModel, GEN_USUARIOS>();

In this Map, there are some properties which are 'int?' (nullable foreign keys) as, for example IDSUPERVISOR.

In order to apply the mapping I use the following sentence:

Mapper.Map<UsuarioViewModel, GEN_USUARIOS>(usuarioVM, usuario);
  • If source has value (5) and destination has not value (null), the value is applied to destination (5).
  • If source has value (6) and destination has another value (5), the value is applied to destination correctly (6).
  • But, if both have the same value (not modifying the value), the property in destination is mapped to NULL, which is wrong!

Is this a bug or there is something I'm missing?

EDIT: I've been able to isolate the problem in a simple project. I have created a repository in GitHub: https://github.com/farlop/TestAutomapper. It includes the code and a SQL script to create the database schema and sample data. To test it just lauch, edit the record which has value in IDSUPERVISOR column and just save without changing any data. You can see how the value is updated to null when it shouldn't

Farlop
  • 690
  • 1
  • 6
  • 20
  • 1
    It is mostly likely that you are missing something. Maybe EF is stepping in and setting it to NULL? This gist works fine. https://gist.github.com/idursun/7248645 – idursun Oct 31 '13 at 12:10
  • You're right. Sure it has to do something with EF. I've tried with another nullable property not mapped to entity and it works fine. I've done a commitment to my test project to reflect this – Farlop Oct 31 '13 at 15:42
  • Trying to refresh the question. Two months after, a colleague of mine has run into the same trouble and we can't find where the problem is. Any idea? – Farlop Dec 16 '13 at 17:29

1 Answers1

0

As stated here, the problem was that there was also a Navigation Property which was also being mapped. As the source object had this property with null value, was overriding the navigation property of the destination object. So, when saving changes to database, EF was updating with null value the foreign key property.

Farlop
  • 690
  • 1
  • 6
  • 20