【问题标题】:Get primitive, complex, ArrayEnumerable types获取原始、复杂、ArrayEnumerable 类型
【发布时间】:2011-04-16 07:38:12
【问题描述】:

我的每个数据库实体都有一个单独的类,当我创建我的类的对象来引用类的属性时,它返回一个循环引用,其中也包含通过 FK 相关的其他实体的属性...要删除循环引用,我想首先通过“上下文代理对象”复制对象的副本,然后获取该对象的原始、复杂、arrayEnumerable 类型并从对象中剥离这些类型,然后对象返回网络服务....

【问题讨论】:

  • 我建议你为你想要实现的目标编写一些代码示例。您对问题的描述不够清楚(至少对我而言)。

标签: c# reflection


【解决方案1】:

听起来像是递归的浅克隆。我已经使用了以下但只有一层深。

public static class EntityBaseExtensions
{
    /// <summary>
    /// Description:    Creates a non-recursive shallow copy of an entity, only including public instance properties decorated with ColumnAttribute.
    ///                 This will return an object without entity references.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source"></param>
    /// <returns>A non-recursive shallow copy of a LINQ entity</returns>
    public static T ShallowClone<T>(this T source) where T : EntityBaseClass
    {
        // create an object to copy values into
        T destination = Activator.CreateInstance<T>();

        // get source and destination property infos for all public instance
        PropertyInfo[] sourcePropInfos = source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
        PropertyInfo[] destinationPropInfos = source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (PropertyInfo sourcePropInfo in sourcePropInfos)
        {
            if (Attribute.GetCustomAttribute(sourcePropInfo, typeof(ColumnAttribute), false) != null)
            {
                PropertyInfo destPropInfo = destinationPropInfos.Where(pi => pi.Name == sourcePropInfo.Name).First();

                destPropInfo.SetValue(destination, sourcePropInfo.GetValue(source, null), null);
            }
        }

        return destination;
    }

}

【讨论】:

    猜你喜欢
    • 2010-12-06
    • 2011-03-14
    • 2011-11-20
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2017-03-05
    • 2011-02-22
    相关资源
    最近更新 更多