Automapper: map List<string> to List<Class> - automapper

How can I map a List<string> to List<Class>?
Usecase: from the Webservice I'm getting a class with a list of string but in my MVC Viewmodel, I want to have Class instead with a single property, which has the value of the string. That way I can add Validation attributes to the property.
I have the way how I convert the List into a List, however I can't get the other way around to work.
Any simple solutions?

The way to do this with AutoMapper is to use .ConstructUsing:
Mapper.CreateMap<string, Class>()
.ConstructUsing(str => new Class { MyProp = str });
Example: https://dotnetfiddle.net/0Vlc8b

You can easily do it with Linq.
var newList = oldList.Select(x => new Item(x)).ToList();

You could do this:
void Main()
{
AutoMapper.Mapper.CreateMap<string,A>()
.ForMember(a => a.Name, m => m.MapFrom(s => s));
new[] {"A", "B"}.Select (AutoMapper.Mapper.Map<A>).Dump();
}
class A
{
public string Name { get; set; }
}
(Linqpad code)
But I think this can go down as a textbook example of over-engineering. Just do it as in Daniel's example.

Related

Cucumber V5-V6 - passing complex object in feature file step

So I have recently migrated to v6 and I will try to simplify my question
I have the following class
#AllArgsConstructor
public class Songs {
String title;
List<String> genres;
}
In my scenario I want to have something like:
Then The results are as follows:
|title |genre |
|happy song |romance, happy|
And the implementation should be something like:
#Then("Then The results are as follows:")
public void theResultsAreAsFollows(Songs song) {
//Some code here
}
I have the default transformer
#DefaultParameterTransformer
#DefaultDataTableEntryTransformer(replaceWithEmptyString = "[blank]")
#DefaultDataTableCellTransformer
public Object transformer(Object fromValue, Type toValueType) {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.convertValue(fromValue, objectMapper.constructType(toValueType));
}
My current issue is that I get the following error: Cannot construct instance of java.util.ArrayList (although at least one Creator exists)
How can I tell cucumber to interpret specific cells as lists? but keeping all in the same step not splitting apart? Or better how can I send an object in a steps containing different variable types such as List, HashSet, etc.
If I do a change and replace the list with a String everything is working as expected
#M.P.Korstanje thank you for your idea. If anyone is trying to find a solution for this here is the way I did it as per suggestions received. Inspected to see the type fromValue has and and updated the transform method into something like:
if (fromValue instanceof LinkedHashMap) {
Map<String, Object> map = (LinkedHashMap<String, Object>) fromValue;
Set<String> keys = map.keySet();
for (String key : keys) {
if (key.equals("genres")) {
List<String> genres = Arrays.asList(map.get(key).toString().split(",", -1));
map.put("genres", genres);
}
return objectMapper.convertValue(map, objectMapper.constructType(toValueType));
}
}
It is somehow quite specific but could not find a better solution :)

Retrieve class parameter using a string in Dart

Let's say that I have a class in Dart that looks like this:
class Hello {
final name;
Hello({this.name});
}
I could create an instance of this class using:
var x = new Hello(name: "General Kenobi");
In Javascript, I could retrieve the name property with syntax like this:
console.log(x["name"]);
Is there a way to do the equivalent in Dart? I.e
print(x["name"]);
I've looked at the docs and can't find anything, would appreciate help from someone who knows. Many thanks.
The easiest way is to create a method, which converts a class to Map and overload [] operator:
class Hello {
final name;
Hello({this.name});
Map<String, dynamic> toMap() => {'name': name};
operator [](String field) => toMap()[field];
}

Conflicts in AutoMapper and AutoFixture

I have 2 classes, Class1 should be mapped to Class2. I do mapping with AutoMapper. I'd like to test my configuration of the mapper and for this purposes I'm using AutoFixture. Source class Class1 has property of type IList<>, destination class Class2 has a similar property but of type IEnumerable<>. To simplify test preparation I'm using AutoFixture (with AutoMoqCustomization) to initialize both source and destination objects. But after initializing property of type IEnumerable<> with AutoFixture, AutoMapper can't map the property.
Error text:
Error mapping types.
Mapping types: Class1 -> Class2 ConsoleApplication1.Class1 ->
ConsoleApplication1.Class2
Type Map configuration: Class1 -> Class2 ConsoleApplication1.Class1 ->
ConsoleApplication1.Class2
Property: Items
Could anybody help me to configure either AutoMapper or AutoFixture to make the mapping work? As a workaround I can assign null to the destination property, but I do not want to do this in the each test.
Simplified example of code:
public class AutoMapperTests
{
public static void TestCollectionsProperty()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ItemClass1, ItemClass2>();
cfg.CreateMap<Class1, Class2>();
});
var src = new Class1();
src.Items = new List<ItemClass1>()
{
new ItemClass1() { Text = "111" },
new ItemClass1() { Text = "222" }
};
var fixture = new Fixture();
var dst = fixture.Create<Class2>();
Mapper.Map(src, dst); //Error at this line of code
}
}
public class Class1
{
public IList<ItemClass1> Items { get; set; }
}
public class Class2
{
public IEnumerable<ItemClass2> Items { get; set; }
}
public class ItemClass1
{
public string Text { get; set; }
}
public class ItemClass2
{
public string Text { get; set; }
}
It's not really an AutoFixture issue per se. You can reproduce it without AutoFixture by instead creating dst like this:
var dst = new Class2();
dst.Items = Enumerable.Range(0, 1).Select(_ => new ItemClass2());
This will produce a similar error message:
Unable to cast object of type 'WhereSelectEnumerableIterator2[System.Int32,Ploeh.StackOverflow.Q45437098.ItemClass2]' to type 'System.Collections.Generic.IList1[Ploeh.StackOverflow.Q45437098.ItemClass2]'
That ought to be fairly self-explanatory: WhereSelectEnumerableIterator<int, ItemClass2> doesn't implement IList<ItemClass2>. AutoMapper attempts to make that cast, and fails.
The simplest fix is probably to avoid populating dst:
var dst = new Class2();
If you must use AutoFixture for this, you can do it like this:
var dst = fixture.Build<Class2>().OmitAutoProperties().Create();
Unless the Class2 constructor does something complex, however, I don't see the point of using AutoFixture in that scenario.
If, on the other hand, you do need dst to be populated, you just need to ensure that dst.Items is convertible to IList<ItemClass2>. One way to do that would be like this:
var dst = fixture.Create<Class2>();
dst.Items = dst.Items.ToList();
You could create a Customization to make sure that this happens automatically, but if you need help with that, please ask a new question (if you don't find one that already answers that question).
Here is a working example for your problem. As #Mark Seemann already told, Mapper.CreateMap has been deprecated, so this example is using the new structure.
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ItemClass1, ItemClass2>();
cfg.CreateMap<Class1, Class2>();
});
var src = new Class1();
src.Items = new List<ItemClass1>()
{
new ItemClass1() { Text = "111" },
new ItemClass1() { Text = "222" }
};
var dest = Mapper.Map<Class1, Class2>(src);
AM requires IList because you're mapping to an existing list and that works by calling IList.Add.

How to map multiple list to a single list?

I have few classes and they have multiple list items like below:
public class Request1
{
public List<AdditionalApplicantData> AdditionalApplicantData { get; set;}
public List<ApplicantData> ApplicantData { get; set; }
}
public class Request2
{
public List<ApplicantDetails> ApplicantData { get; set; }
}
I want to map Request1 to Request2 but List of ApplicantData has to be mapped from multiple sources like List of ApplicantData & List of AdditionalApplicantData but not sure how to achieve it can someone please help me here?
You can use function below with createMap() function. Source: https://github.com/AutoMapper/AutoMapper/wiki/Before-and-after-map-actions
.AfterMap((src, dest) => {
dest.ApplicantData = /*your logic here*/
});
And you should mark ApplicantData as don't map because you have a variable named ApplicantData at the source class. You should implement the logic yourself.
EDIT:
When you are initializing mapper, you create map for each object. So for your case it would be like:
Mapper.Initialize(cfg => {
cfg.CreateMap<Request1, Request2>()
.ForMember(x => x.ApplicantData, opt => opt.Ignore()) //You want to implement your logic so ignore mapping
.AfterMap((src, dest) =>
{
dest.ApplicantData = /*implement your logic here*/
});
});
public class ApplicantDetailsResolver : IValueResolver<Request1, Request2, List<ApplicantDetails>>
{
public List<ApplicantDetails> Resolve(Request1 source, Request2 destination,List<ApplicantDetails> destMember, ResolutionContext context)
{
destination.ApplicantDetails = context.Mapper.Map<List<ApplicantDetails>>(source.ApplicantData);
for (int i = 0; i < destination.ApplicantDetails.Count(); i++)
{
context.Mapper.Map(source.AdditionalApplicantData.ElementAt(i), destination.ApplicantDetails.ElementAt(i));
}
return destination.ApplicantDetails;
}
}
I have written above custom value resolver for mapping list from multiple sources and its working fine but problem, is it can't match properties which are differently named, is there way I can handle this scenario as well?

How to Implicitly Convert an Enumerable of a type with Implicit Conversion Operators in C# 4.0

Given:
public struct Id
{
readonly int m_id;
public Id(int id)
{ m_id = id; }
public static implicit operator int(Id id)
{ return id.m_id; }
public static implicit operator Id(int id)
{ return new Id(id); }
}
Can you implicitly convert an
IEnumerable<int>
to
IEnumerable<Id>
and vice versa. In some way. Note that
var ids = new int[]{ 1, 2 };
ids.Cast<Id>();
does not appear to work and covariance does not appear to be working in this case, either. Of course, doing a select will work i.e.:
ids.Select(id => new Id(id));
But I am looking for something that would make this work implicitly, so writing:
IEnumerable<Id> ids = new int[]{ 1, 2 };
And yes, I know this can be written as:
IEnumerable<Id> ids = new Id[]{ 1, 2 };
But the issue is in cases where the enumerable of ints comes from a different source, such as a file for example.
I am sorry if there already is an answer for this, but I could not find it.
According to this answer what you want is not possible. But you can get close by not implicitly casting your id but your collection. Like this :
public class Ids : List<int>
{
public static implicit operator Ids(int[] intArray)
{
var result = new Ids();
result.AddRange(intArray);
return result;
}
}
then this is possible :
Ids t = new [] { 3,4 };
What's wrong with:
IEnumerable<int> data = GetDataFromSource();
IEnumerable<Id> ids = data.select(id => new Id(id));

Resources