使用反射 c# 映射业务对象和实体对象 [英] Mapping business Objects and Entity Object with reflection c#

查看:17
本文介绍了使用反射 c# 映射业务对象和实体对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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; }
    }

我的实体类具有相同的属性,CategoryId 和 CategoryName.任何使用反射或动态的最佳实践将不胜感激.

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

推荐答案

您可以使用 AutomapperValueinjecter

好的,我写了一个使用反射的函数,注意它不会处理映射属性不完全相等的情况,例如 IList 不会与 List 映射

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);                   
    }            
}

这篇关于使用反射 c# 映射业务对象和实体对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆