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

查看:246
本文介绍了映射业务对象和实体对象与反思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.Any最佳实践的动态将是AP preciated。

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

推荐答案

您可以使用 Automapper Valueinjecter

编辑:

好吧,我写了使用反射功能。

Ok I wrote a function that uses reflection.

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天全站免登陆