Gnegno
Gnegno

Reputation: 366

Automapper - How to map a private backing field

i'm trying to use Automapper in this scenario. I've got an Entity (DDD entity object) that must have private setters for all the properties and collections and i have to map it to a simpler object that will be stored in DB using. The Entity have a code like that:

    public class TypeA : Entity
{
    private List<TypeB> _assignedItems;
    public IEnumerable<TypeB> AssignedItems
    {
        get { return _assignedItems.ToList(); }
    }

    public string Name { get; private set; }

    public string Description { get; private set; }

    ...etc...
}`

And the Persistence-friendly object

[Table("TypeA")]
public class TypeADao : EntityDao
{
    public string Name { get; set; }

    public string Description { get; set; }

    public ICollection<TypeBDao> AssignedItems { get; set; }
}

With Automapper can easily Map the Entity to the Dao, but i fail to do the opposite, as i need to map AssignedItems to the private backing field _assignedItems in the Entity. How can i do that? Is there a way to map the AssignedItems collection to the private field called _assignedItems? Many thanks to all

Upvotes: 2

Views: 3641

Answers (1)

HExit
HExit

Reputation: 696

I know this might come a bit too late, but should still be helpful for people who might encounter this problem in the future.

Here is how I solved the mapping private field problem.

// Please refer to https://github.com/AutoMapper/AutoMapper/issues/600
// Please refer to https://github.com/AutoMapper/AutoMapper/issues/946
ShouldMapField = fieldInfo => !fieldInfo.IsDefined(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute));
ShouldMapProperty = propertyInfo => true;

Upvotes: 5

Related Questions