Offir
Offir

Reputation: 3491

EF Core entity is added instead of update when using AutoMapper

I try to update a Text that has Seo navigation property.

Texts text = await _context.Texts.Include(x => x.Seo).Where(x => x.Id == id).FirstOrDefaultAsync();
text.Seo = _mapper.Map<Seo>(text);
await _unitOfWork.SaveChangesAsync();

Mapper:

         CreateMap<Texts, Seo>()
         // If I won't ignore I will get an error: 
         // "ensure that only one entity instance with a given key value is attached."
        .ForMember(dest => dest.Id, opt => opt.Ignore())

        .ForMember(dest => dest.Image, opt => opt.MapFrom(src => src.Image.InverseParent.OrderByDescending(x => x.Width).FirstOrDefault()))
        .ForMember(dest => dest.KeyWords, opt => opt.MapFrom(src => src.Title.ToKeywords()))
        .ForMember(dest => dest.LanguageType, opt => opt.MapFrom(src => src.LanguageType))
        .ForMember(dest => dest.OgTitle, opt => opt.MapFrom(src => src.Title))
        .ForMember(dest => dest.OgDescription, opt => opt.MapFrom(src => src.Description));

After SaveChanges a new row of Seo is created in the database each time.
When I don't use AutoMapper and set the values like this, the correct Seo entity is modified in the database as expected.

     text.Seo.Image = text.Image.InverseParent.OrderByDescending(x => x.Width).FirstOrDefault();
     text.Seo.KeyWords = text.Title.ToKeywords();
     text.Seo.LanguageType = text.LanguageType;
     text.Seo.OgTitle = text.Title;
     text.Seo.OgDescription = text.Description;

     await _unitOfWork.SaveChangesAsync();

How can I keep using AutoMapper without creating a new entity?

Upvotes: 0

Views: 821

Answers (1)

Okan Karadag
Okan Karadag

Reputation: 3045

mapper.map<Seo>(text) can't relate the entity because it makes new model.

you can try this:

_mapper.map(text,text.Seo); //don't assign to variable

Upvotes: 2

Related Questions