سؤال

So i have this;

public class Parent
{
  public string SomeProperty { get; set; }
  public Child ChildProperty { get; set; }
}
public class Child
{
  public string ChildProperty { get; set; }
  public string OtherChildProperty { get; set; }
}
public class Flat
{
  public string SomeProperty { get; set; }
  public string ChildProperty { get; set; }
}

And then I do this;

Flat source = new Flat { SomeProperty = "test", ChildProperty = "test" };
Parent dest = GetParentFromDataContext();

Mapper.Map<Flat,Parent>(source,dest);

Then my expectation is that dest.ChildProperty.OtherChildProperty is still set to whatever it was when it was pulled from the datacontext. However I'm struggling to do this.

If I CreateMap as so, then I get a "must resolve to top-level member" exception;

Mapper.CreateMap<Flat,Parent>()
  .ForMember(dest => dest.Parent.ChildProperty.ChildProperty,
    options => options.MapFrom(source => source.ChildProperty))
  .ForMember(dest => dest.Parent.ChildProperty.OtherChildProperty,
    options => options.Ignore());

However if I do the following, then the new Child {} replaces the Child pulled from the datacontext essentially clearing OtherChildProperty;

Mapper.CreateMap<Flat,Parent>()
  .ForMember(dest => dest.Child
    options => options.MapFrom(source => new Child { ChildProperty = source.ChildProperty } ));

How can i map this and preserve the child properties I wish to ignore?

هل كانت مفيدة؟

المحلول 2

Inelegant, but this works;

Mapper.CreateMap<Flat,Parent>()
  .ForMember(dest => dest.ChildProperty, options => options.Ignore());
Mapper.CreateMap<Flat,Child>()
  .ForMember(dest => dest.OtherChildProperty, options => options.Ignore());

Mapper.Map<Flat,Parent>(source,dest);
Mapper.Map<Flat,Child>(source,dest.Child);

نصائح أخرى

You are trying to reverse flattening process with automapper and that is just wrong tool for the job. See this SO question.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top