0

Is it possible with automapper in C# to map the properties of an object to an array/dictionary? 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. Possible? If so, what is the correct way to do this? Thanks.

2
  • Does it have to use AutoMapper? Commented Feb 16, 2011 at 17:48
  • not necessarily. i could make my own mapper too... Commented Feb 16, 2011 at 17:52

1 Answer 1

5

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.