我们在写代码过程中,常常需要把一个实体中的字段值赋值到另一个实体中,尤其是当字段特别多的时候,一系列的取值加判空,是相当的累,而且写的代码也会非常的丑;
以下方法可以相对完美的解决这个问题,希望能给大家带来帮助与启发,好用的就点个赞收藏一下
//NEW一个目标实体
var trans = new Entity("mcs_vehownertransfer");
//罗列需要MAPPING的字段名,以","间隔
var attrs = "mcs_userid,mcs_mobilephone,mcs_idtype,mcs_identitycard,mcs_gender,mcs_birthdate," +
"mcs_address,mcs_homeaddress,mcs_workaddress,mcs_telephone1,mcs_telephone2,ownerid";
//MAPPING
trans = vehowner.Mapping(trans, attrs);
//差异字段名补充
trans["mcs_vehowner"] = vehowner.ToEntityReference();
trans["mcs_name"] = vehowner.GetAttributeValue<string>("mcs_fullname");
trans["mcs_email"] = vehowner.GetAttributeValue<string>("mcs_email1");
service.Create(trans)
//以下为MAPPING方法实现
/// <summary>
/// mapping entity source to target
/// </summary>
/// <param name="source"> </param>
/// <param name="target"> </param>
/// <param name="attributes">attribute join with ,</param>
/// <returns></returns>
public static Entity Mapping(this Entity source, Entity target, string attributes)
{
foreach (var attr in attributes.Split(','))
{
if (!source.Contains(attr)) continue;
var value = source.Attributes[attr];
if (null == value) continue;
var type = value.GetType();
if (type == typeof(OptionSetValue))
{
target[attr] = source.GetAttributeValue<OptionSetValue>(attr);
}
else if (type == typeof(EntityReference))
{
target[attr] = source.GetAttributeValue<EntityReference>(attr);
}
else if (type == typeof(Byte[]))
{
target[attr] = source.GetAttributeValue<byte[]>(attr);
}
else
{
target[attr] = value;
}
}
return target;
}