gpt4 book ai didi

.net - 使用反射 c# 映射业务对象和实体对象

转载 作者:行者123 更新时间:2023-12-02 05:31:42 24 4
gpt4 key购买 nike

我想在 C# 中使用反射以某种方式将实体对象映射到业务对象 -

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

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

最佳答案

您可以使用 AutomapperValueinjecter

编辑:

好吧,我写了一个使用反射的函数,注意它不会处理映射属性不完全相等的情况,例如 IList 不会映射到 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);
}
}

关于.net - 使用反射 c# 映射业务对象和实体对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5235784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com