I am having trouble finding the right approach to creating a complex ViewModel.
Model Class B:
public class A{public int A_id;}
public class B{
public int B_id;
public string Name;
public virtual ICollection<A> A_Items;
}
ViewModel Class C:
public class C {public int B_id; public CountOfA;}
So I am am trying to find another way to include the number of occurrences of A in B's class and put that into ViewModel class C. Currently I can do that with creating Custom IResolver class, like this.
CreateMap<B,C>().ForMember(dest => dest.CountOfA, opt => opt.ResolveUsing<ListToCountResolver>());
so then in the controller I use the "Include" method to include "A_Items", and this works fine. But there got to be a better way of doing it, not get getting the entire list from the DB when all I want is a simple COUNT(*) of the rows. Or do I have to create a custom resolver every time I am trying to get some custom value from the B class. Getting the count of the rows is just an example, but what if I wanted to convert the "Name" of "A" Collection into a single string using AutoMapper separated with comma. would that be possible? FYI,I am fairly new to the MVC world, and I am trying to stay with the "Lean Controller","Fat Model", and "Dummy View" design suggestion, so I can follow the good practices. Thanks for your input.
Can you use simple MapFrom
implementation, that could look something like this:
Mapper.CreateMap<B, C>().ForMember(dest => dest.CountOfA, opt => opt.MapFrom(src => src.A_Items.Count()));
I have created a small unit test and it works fine.
var b = new B {A_Items = new Collection<A>{new A(), new A(), new A()}, B_id = 1};
var c = Mapper.Map<C>(b);
c.CountOfA.Should().Be(3);
c.B_id.Should().Be(1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.