Mapping business Objects and Entity Object with reflection c#
11,689
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);
}
}
Author by
Hidsman
Updated on June 05, 2022Comments
-
Hidsman almost 2 years
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.
-
Hidsman about 13 yearsi dont want to use any third party or open source
-
Hidsman about 13 yearsstring destinationPropertyName = LookupMapping(sourceType.ToString(),destinationType.ToString(),sourceProperty.Name ) ; Here LookupMapping is Microsoft Dynamic CRM Function. how i can do it without CRM
-
Hidsman about 13 yearsi need to use reflection to avoid fix number of properties.
-
Serguzest about 13 yearsI wonder what makes you think it doesn't use reflection? GetValue, SetValue those are reflection methods.
-
Omu about 13 years@Aaabb Bbaa with Valueinjecter you would do a.InjectFrom(b) and that's it
-
Michael about 12 yearsI recently started working on a new project and found a copied version of this code in it. I would strongly recommend using AutoMapper or ValueInjecter as @Serguzest initially suggested as this piece of code created problems in our applications. For example, a List<string> would be null in the destination.
-
GiveEmTheBoot almost 10 yearsTried your solution (in VB.NET but it's the same). I've added "If match.dp.CanWrite Then" in the foreach cycle. Destination property could not have a setter. I also changed the method signature in this way to make the method more typed: "Public Shared Sub MapObjects(Of T, S)(source As T, destination As S)". Hope it helps.