anıl yıldırım
anıl yıldırım

Reputation: 963

How can i set the external data that not exist dto object to domain on automapper

I am using Dto for data transfer view to domain and use automapper for mapping. My problem is, the property that not exist dto but i need to set before mapping to domain. I have tried to use Linq query to get external data from db on before and after mapping methods but linq query giving error.

Sample below

FooDto

public class FooDto 
{
public int MyProperty1 {get;set;}
}

FooDomain

public class Foo 
{
public int MyProperty1 {get;set;}
public int MyProperty2 {get;set;}
public int Foo2ID {get;set;}
public virtual Foo2 Foo2 {get;set;}
}

Foo2Domain

public class Foo2
{
public int ID {get;set;}
public int MyProperty1 {get;set;}
}

**AutoMapper*

Mapper.Initialize(x =>
{
x.CreateMap<FooDto, Foo>().BeforeMap(
(src, dest) =>dest.MyProperty2 = dest.Foo2.MyProperty1);
}

I want to set Foo2.MyProperty1 to Foo.MyProperty2 using mapping.

Upvotes: 0

Views: 414

Answers (1)

Woot
Woot

Reputation: 1809

This answer might need to be edited if my assumptions are wrong. The assumption I am making is that the source object has the right data. Based on your sample it looks like your source object's MyProperty2 can be set in the destination object so do map this all you would need to do is:

Mapper.Initialize(x =>
{
    x.CreateMap<FooDto, Foo>()
    .ForMember(dest => dest.MyProperty2, opt => opt.MapFrom(src => src.MyProperty1))
    .ForMember(dest => dest.Foo2.MyProperty1, opt => opt.MapFrom(src => src.MyProperty1));
}

What this code does is it tells AutoMapper when I give you an object of Type FooDto and I am requesting an object of Type Foo. For the destination objects property 'Foo2.MyProperty1' and 'MyProperty2', use the options method MapFrom. Go to the source Object get the MyProperty1 and assign it's value to my destination objects MyProperty2 and Foo2.MyProperty1.

I think this would fix you up.

Right sorry I corrected the answer

Upvotes: 1

Related Questions