I'am using ValueInjector(3.x) over AutoMapper but I have some questions.
First, I don't understand the difference between UnflatLoopInjection
and FlatLoopInjection
.
Also i want to set values in complex types.
Class Product {
public string Id { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
}
Class ProductDTO {
public string Name { get; set; }
public Category Category { get; set; }
}
var product = repository.Get(id);
product.InjectFrom(dto);
The problem is my product.Category
already have some properties with values and using InjectFrom the value injector replace the product.Category
to dto.Category
replacing the entire category even replacing to null
.
Thanks
flattening is when you go from
Foo1.Foo2.Foo1.Name to Foo1Foo2Foo1Name
unflattening the other way around
I understand that you want to avoid injecting when the source property is Null
for this you can create an injections like this:
public class AvoidNullProps : LoopInjection
{
protected override void SetValue(object source, object target, PropertyInfo sp, PropertyInfo tp)
{
var val = sp.GetValue(source);
if(val != null)
tp.SetValue(target, val);
}
}
and use it
res.InjectFrom<AvoidNullProps>(src);
you could also use the Mapper:
Mapper.AddMap<ProductDTO, Product>(dto =>
{
var res = new Product();
res.Id = dto.Id;
res.Name = dto.Name;
if(dto.Category != null && dto.Category.Id != null)
res.Category = Mapper.Map<Category>(dto.Category);
return res;
});
var product = Mapper.Map<Product>(dto);