I use Mapster package for mapping two objects. An existing object is updated (patched) by applying some rules in the source object and ignore some properties based on their values and Property Type using a function.
I try to use the method IgnoreMember((member, side)
to ignore members.
The function return false when ignoring member, like the code below:
//sourceValue: the value of the property (member) in the object
//Return: true: map members, false: ignore members
bool validMembers(object sourceValue)
{
if (sourceValue is null) return false;
switch (sourceValue)
{
//ignore string null or empty
case string { Length: > 0 }:
return true;
//ignore empty collection
case ICollection { Count: > 0 } l:
return true;
case bool b:
return b;
case int i:
return i != 0;
//.....
// other rules
default:
return false;
}
}
Mapster is configured as in the next code:
static void Test1()
{
//the object that is required to be updated:
var destination = new Foo{Name = "bar"}; //actually it's created from json string.
//the source object used to update destination object.
var source = new Foo{Name="", Address="city", Kind = Kind.Male, Cert = new List<string>() {"c1", "c2"}};
//****** Configuration********************
//global setting
//THIS LINE NEED TO BE CORRECTED
TypeAdapterConfig.GlobalSettings.Default
.IgnoreMember((member, side) => !validMembers(what_member_property????)); //What the parameter that should be passed and have the value of member !!!
TypeAdapterConfig<Foo, Foo>.NewConfig().IgnoreNullValues(true);
//Mapping to an existing object
source.Adapt(destination);
}
}
class Foo
{
public string Name { get; set; }
public string Address { get; set; }
public Kind Kind { get; set; }
public IEnumerable<string> Cert { get; set; }
}
enum Kind
{
UnDefined,
Male,
Female
}
In the method IgnoreMember((member, side) => !validMembers(member))
, I don't find an api in the documentation that is represent the value of the member to be passed to the my ValidMembers function
.
The Question:
What the member parameter that should be passed to the function ValidMembers? Is there any other way to apply these rules (not member to member mapping)?
I have provided dotnetfiddle to show the issue.