开发者

How to MapFrom a collection? Auto mapper

开发者 https://www.devze.com 2023-02-13 05:24 出处:网络
I have a linq to sql object that has some references to some other tables I am trying to map it to a vm but nothing ever gets captures.

I have a linq to sql object that has some references to some other tables

I am trying to map it to a vm but nothing ever gets captures.

Mapper.CreateMap<A, G>();


// A is the linq to sql object
A.MyList // this is a collection that I am trying to get the value out of A.MyList.Id

// G is my View Model
public class G
{
   public string AMyListId {get; set;}

}


 vm = Mapper.Map<List<A>, List<G>>(aListOfAFromDb);

This always comes back from null. I thought I would have to do it manually so I tried

Mapper.CreateMap<A, G>().ForMember(dest => dest.AMyList , opt => opt.MapFrom(src =>????));

but sinc开发者_如何学运维e I am getting it from a list it won't give any of the properties to choose from.

Edit

I realized that I should not have a list of "MyList" it should be a one to one. I still am having problems trying to do what I want to do.

I have this

Mapper.CreateMap();

A.Vip.UserId // again my linq object is A

// G is my View Model
public class G
{
   public string IsVip {get; set;}

}


 vm = Mapper.Map<List<A>, List<G>>(aListOfAFromDb);

 Mapper.CreateMap<A, G>().ForMember(dest => dest.IsVip, opt => opt.AddFormatter<VipFormatter>());


public class VipFormatter : IValueFormatter
    {
        public string FormatValue(ResolutionContext context)
        {
            bool value = (bool)context.SourceValue;

            if (value)
            {
                return "Yes";
            }


            return "No";

        }
    }

yet nothing every gets bound. I am not sure why. Do I have to do change my property to "AVipUserId"? Or somehow tell it to map?


From what I can see in your code, and in addition to my comment above, you don't need AutoMapper for this one:

List<A> dbItems;
IEnumerable<G> results = dbItems.Select(x => x.MyList.MyListID);

In fact, you can't map A to G, because you're going to create multiple "G" objects for each "A" object.

Let me know if I misunderstood the question here.

UPDATE:

I would change "G" to use a boolean property and then do the following:

Mapper.CreateMap<A, G>().ForMember(dest => dest.IsVip, opt => opt.MapFrom(src => src.Vip == null));

Or, whatever logic you use to determine if it is a VIP or not.


How about:

List<G> items = // whatever
var result = items.Select(g => Mapper.Map<G, A>(g));
0

精彩评论

暂无评论...
验证码 换一张
取 消