Quantum
Quantum

Reputation: 1476

Using Automapper to make full copy of an object with IList properties

So I need to make copies of objects. I have a model here "place" that has a IList HasAndBelongsToMany Property that is being a pain. I need to take the field property and copy it too but it copies the reference only. Here is what i have

public class place : ActiveRecordBase<place>
{
    public place() {  }

    private int place_id;
    [PrimaryKey("place_id")]
    virtual public int id
    {
        get { return place_id; }
        set { place_id = value; }
    }
    private IList<fields> Fields;
    [HasAndBelongsToMany(typeof(fields), Lazy = true, Table = "place_to_fields", ColumnKey = "place_id", ColumnRef = "field_id", NotFoundBehaviour = NotFoundBehaviour.Ignore, Cascade = ManyRelationCascadeEnum.AllDeleteOrphan)]
    virtual public IList<fields> field
    {
        get { return Fields; }
        set { Fields = value; }
    }
}

And use automapper like this

place org = ActiveRecordBase<place>.Find(id);

Mapper.Reset();
Mapper.CreateMap<place, place>().ForMember(dest => dest.id, o => o.Ignore())
                                .ForMember(dest => dest.field, o => o.Ignore())
                                ; 
place copy = new place();
Mapper.Map(org, copy);

copy.SaveAndFlush();

Which works because i'm skiping the field. What i was hoping for was something more like:

Mapper.CreateMap<place, place>().ForMember(dest => dest.id, o => o.Ignore())
                                .ForMember(dest => dest.field.id, o => o.Ignore())
                                ; 

See the first line with .ForMember(dest => dest.id, o => o.Ignore()) is so that I don't copy the reference id for the place object. I need to do the same for the place property field. I need to ignore the id's and make new entries with the same values on the rest of its properties

Upvotes: 1

Views: 6518

Answers (1)

k0stya
k0stya

Reputation: 4315

You need to create mapping for field type and add "Ignore" option for field's id like you've alredy done for place type.

Mapper.CreateMap<fields, fields>().ForMember(dest => dest.id, o => o.Ignore());
Mapper.CreateMap<place, place>().ForMember(dest => dest.id, o => o.Ignore());

Upvotes: 0

Related Questions