Uncharted
Uncharted

Reputation: 267

Automapper after mapping to existing object ef core can't track changes

After pulling the list of objects(entities) from the database, I want to update those objects but only certain properties and save changes to DB, after mapping is done it lose track of changes and context is not showing any changes.

I tried making custom value resolver for AutoMapper and I failed miserably since ips are still 0 after mapping.

So here is the code snippet

class A { int id; string Name; }
class B { string Name;} 
List<B> b = new List<B>() { "t", "g" };

var result = ctx.A.ToList();
this.Mapper.Map<IList<B>,IList<A>>(b,result);
ctx.A.SaveChanges();

Upvotes: 0

Views: 1993

Answers (1)

Erik Philips
Erik Philips

Reputation: 54628

The problem is that you are using a List of items.

this.Mapper.Map<IList<B>,IList<A>>(b,result);

Says, map B values to result values... but don't change result to a new object type, which it isn't. Nothing in this code tells AutoMapper not to change the items in the list.

This is because there is no way for Automapper to correlation which items in b should map to which items in result. Additionally, what should it do if the number of items are different?

You can force it yourself using:

result = result
  .Zip(b, (r,b2) => mapper.Map<B,A>(b2,r) )
  .ToList()

DotNetFiddleExample

Upvotes: 1

Related Questions