Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

.net - Mapping business Objects and Entity Object with reflection c#

I want to somehow map entity object to business object using reflection in c# -

public class Category
    {
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }
    }

My Entity Class has same properties, CategoryId and CategoryName.Any best practice using reflection or dynamic would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use Automapper or Valueinjecter

Edit:

Ok I wrote a function that uses reflection, beware it is not gonna handle cases where mapped properties aren't exactly equal e.g IList won't map with List

public static void MapObjects(object source, object destination)
{
    Type sourcetype = source.GetType();
    Type destinationtype = destination.GetType();

    var sourceProperties = sourcetype.GetProperties();
    var destionationProperties = destinationtype.GetProperties();

    var commonproperties = from sp in sourceProperties
                           join dp in destionationProperties on new {sp.Name, sp.PropertyType} equals
                               new {dp.Name, dp.PropertyType}
                           select new {sp, dp};

    foreach (var match in commonproperties)
    {
        match.dp.SetValue(destination, match.sp.GetValue(source, null), null);                   
    }            
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...