Mapping business Objects and Entity Object with reflection c#

前端 未结 3 1919
一生所求
一生所求 2020-12-20 02:03

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

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


        
3条回答
  •  无人及你
    2020-12-20 02:26

    This is something that I wrote to do what I think you are trying to do and you don't have to cast your business objects:

    public static TEntity ConvertObjectToEntity(object objectToConvert, TEntity entity) where TEntity : class
        {
            if (objectToConvert == null || entity == null)
            {
                return null;
            }
    
            Type BusinessObjectType = entity.GetType();
            PropertyInfo[] BusinessPropList = BusinessObjectType.GetProperties();
    
            Type EntityObjectType = objectToConvert.GetType();
            PropertyInfo[] EntityPropList = EntityObjectType.GetProperties();
    
            foreach (PropertyInfo businessPropInfo in BusinessPropList)
            {
                foreach (PropertyInfo entityPropInfo in EntityPropList)
                {
                    if (entityPropInfo.Name == businessPropInfo.Name && !entityPropInfo.GetGetMethod().IsVirtual && !businessPropInfo.GetGetMethod().IsVirtual)
                    {
                        businessPropInfo.SetValue(entity, entityPropInfo.GetValue(objectToConvert, null), null);
                        break;
                    }
                }
            }
    
            return entity;
        }
    

    Usage example:

    public static Category GetCategory(int id)
        {
            return ConvertObjectToEntity(Database.GetCategoryEntity(id), new Category());
        }
    

提交回复
热议问题