简体   繁体   English

使用AutoMapper将对象字段映射到数组?

[英]Using AutoMapper to map object fields to array?

Is it possible with automapper in C# to map the properties of an object to an array/dictionary? C#中的automapper是否可以将对象的属性映射到数组/字典? I have tried the following: 我尝试了以下方法:

Mapper.CreateMap<FFCLeads.Models.FFCLead, Dictionary<string, SqlParameter>>()
    .ForMember(d => d["LeadID"], o => o.MapFrom(s => new SqlParameter("LeadID", s.LeadID)))
    .ForMember(d => d["LastName"], o => o.MapFrom(s => new SqlParameter("LastName", s.LastName)));

However, it does not work (object ref not set to an instance). 但是,它不起作用(对象引用未设置为实例)。 Basically, I'm trying to make the values of this object to an array of SqlParameter objects. 基本上,我试图将此对象的值设置为SqlParameter对象的数组。 Possible? 可能? If so, what is the correct way to do this? 如果是这样,正确的方法是什么? Thanks. 谢谢。

I use the following method: 我使用以下方法:

IDictionary<string, object> GetDictionaryFromObject(object obj)
{
    if(obj == null) return new Dictionary<string, object>();
    return obj.GetType().GetProperties().
                ToDictionary(p => p.Name,
                             p => p.GetValue(obj, null) ?? DBNull.Value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM