映射业务对象和实体对象与反射C#
问题描述:
我想在C#中使用反射实体对象以某种方式映射到业务对象 -映射业务对象和实体对象与反射C#
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
}
我的实体类具有相同的属性,类别编号和CategoryName.Any最佳实践使用反射或动态将不胜感激。
答
您可以使用Automapper或Valueinjecter
编辑:
好吧,我写了使用反射功能,谨防它是不会处理的情况下映射属性是不完全等于例如IList中不会映射与列表
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);
}
}
答
http://automapper.codeplex.com/
我的票是自动映射。我目前使用这个。我已经做了它的性能测试,虽然它是不一样快的手绘图(下图):
Category c = new Category
{
id = entity.id,
name = entity.name
};
映射,这种交易自动使它成为一个显而易见的选择,至少对实体业务层映射。我实际上是从业务层手动映射到视图模型,因为我需要灵活性。
答
这一点是我写的做什么,我认为你正在尝试做的,你没有投你的业务对象:
public static TEntity ConvertObjectToEntity<TEntity>(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;
}
用例:
public static Category GetCategory(int id)
{
return ConvertObjectToEntity(Database.GetCategoryEntity(id), new Category());
}
我不想使用任何第三方或开源 – Hidsman 2011-03-08 17:22:15
已更新我的回答 – Serguzest 2011-03-08 17:37:34
string destinationPropertyName = LookupMapping(sourceType.ToString(),destinationType.ToString(),sourceProperty.Name);这里LookupMapping是Microsoft的动态CRM功能。如何在没有CRM的情况下做到这一点 – Hidsman 2011-03-08 18:15:31