使用反射c#映射业务对象和实体对象

Hid*_*man 2 .net entity-framework c#-3.0 c#-4.0

我想以某种方式使用c#中的反射将实体对象映射到业务对象 -

public class Category
    {
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我的实体类具有相同的属性,CategoryId和CategoryName.任何使用反射或动态的最佳实践都将受到赞赏.

Ser*_*est 15

您可以使用AutomapperValueinjecter

编辑:

好吧我写了一个使用反射的函数,要注意它不会处理映射属性不完全相等的情况,例如IList不会映射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);                   
    }            
}
Run Code Online (Sandbox Code Playgroud)