使用Automapper使用IList属性制作对象的完整副本

时间:2012-08-09 14:44:41

标签: c# automapper asp.net-4.0 castle

所以我需要复制对象。我有一个模型在这里“地方”有一个IList HasAndBelongsToMany属性是一个痛苦。我需要获取field属性并复制它,但它只复制引用。这就是我所拥有的

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; }
    }
}

并使用像这样的automapper

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();

哪个有效,因为我正在滑动这个领域。我所希望的更像是:

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

请参阅.ForMember(dest =&gt; dest.id,o =&gt; o.Ignore())的第一行,以便我不复制place对象的引用ID。我需要为place属性字段做同样的事情。我需要忽略id并在其余属性上创建具有相同值的新条目

1 个答案:

答案 0 :(得分:0)

您需要为字段类型创建映射并添加&#34;忽略&#34;字段ID的选项,就像您已经为地点类型做了一样。

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