.net 用反射Map业务对象和实体对象

bxgwgixi  于 2023-06-25  发布在  .NET
关注(0)|答案(4)|浏览(121)

我想在C#中使用反射将实体对象Map到业务对象-

  1. public class Category
  2. {
  3. public int CategoryID { get; set; }
  4. public string CategoryName { get; set; }
  5. }

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

z4bn682m

z4bn682m1#

http://automapper.codeplex.com/
我的票是自动绘图仪。我目前使用这个。我已经对它做了性能测试,虽然它没有手工Map那么快(下图):

  1. Category c = new Category
  2. {
  3. id = entity.id,
  4. name = entity.name
  5. };

自动Map的折衷使其成为一个明显的选择,至少对于实体到业务层的Map来说是这样。实际上,我手动将业务层Map到视图模型,因为我需要灵活性。

nhhxz33t

nhhxz33t2#

这是我写的东西,我认为你正在尝试做的事情,你不需要强制转换你的业务对象:

  1. public static TEntity ConvertObjectToEntity<TEntity>(object objectToConvert, TEntity entity) where TEntity : class
  2. {
  3. if (objectToConvert == null || entity == null)
  4. {
  5. return null;
  6. }
  7. Type BusinessObjectType = entity.GetType();
  8. PropertyInfo[] BusinessPropList = BusinessObjectType.GetProperties();
  9. Type EntityObjectType = objectToConvert.GetType();
  10. PropertyInfo[] EntityPropList = EntityObjectType.GetProperties();
  11. foreach (PropertyInfo businessPropInfo in BusinessPropList)
  12. {
  13. foreach (PropertyInfo entityPropInfo in EntityPropList)
  14. {
  15. if (entityPropInfo.Name == businessPropInfo.Name && !entityPropInfo.GetGetMethod().IsVirtual && !businessPropInfo.GetGetMethod().IsVirtual)
  16. {
  17. businessPropInfo.SetValue(entity, entityPropInfo.GetValue(objectToConvert, null), null);
  18. break;
  19. }
  20. }
  21. }
  22. return entity;
  23. }

用法示例:

  1. public static Category GetCategory(int id)
  2. {
  3. return ConvertObjectToEntity(Database.GetCategoryEntity(id), new Category());
  4. }
展开查看全部
mw3dktmi

mw3dktmi3#

如果你需要高性能的解决方案,反射可能不是正确的选择。除了其他答案,我可以建议使用预编译的表达式,因为它们更有效,并且通过使用它们,您可以从类型安全中受益。你可以在Medium上的article中阅读更多关于这个想法的信息。
您还可以查看TryAtSoftware.Extensions.Reflection-它公开了可以帮助构造适当表达式的扩展方法。它是open-source,可以作为NuGet包使用。

62o28rlo

62o28rlo4#

可以使用AutomapperValueinjecter
编辑:
好的,我写了一个使用反射的函数,注意它不能处理Map的属性不完全相等的情况,例如IList不能Map到List

  1. public static void MapObjects(object source, object destination)
  2. {
  3. Type sourcetype = source.GetType();
  4. Type destinationtype = destination.GetType();
  5. var sourceProperties = sourcetype.GetProperties();
  6. var destionationProperties = destinationtype.GetProperties();
  7. var commonproperties = from sp in sourceProperties
  8. join dp in destionationProperties on new {sp.Name, sp.PropertyType} equals
  9. new {dp.Name, dp.PropertyType}
  10. select new {sp, dp};
  11. foreach (var match in commonproperties)
  12. {
  13. match.dp.SetValue(destination, match.sp.GetValue(source, null), null);
  14. }
  15. }
展开查看全部

相关问题