mercredi 25 août 2021

setting property value of System.Linq.Enumerable not working [duplicate]

I have a class that should set property values.

something like this:

    public class AuditService
    {
        public static void Foo<T>(T entity, int userId = 1, string propertyName= "CreatedBy")
        {
            Console.WriteLine(entity.GetType().IsValueType);

            Type entityType = entity.GetType();
            bool isIEnumerable = entityType.GetInterfaces().Any(x => x.IsGenericType && 
                x.GetGenericTypeDefinition() == typeof(IEnumerable<>));

            if (isIEnumerable)
            {                    
                foreach (var i in (entity as IEnumerable<object>))
                {
                    SetProperty(i);
                }
            }
        }
    }

if T is an Array of objects, it works as expected, but if it's System.Linq.Enumerable, the property values are not being set (in fact it's being set on a copy, not the original object). Here's the SetProperty.

public static void SetProperty(object obj, int userId = 1, string propertyName = "CreatedBy")
{                 
    Type t = obj.GetType();
    PropertyInfo info = t.GetProperty(propertyName);
    if (info != null)
    {
        info.SetValue(obj, userId);
    }
}

this doesn't work:

            int parentId = 1;
            IEnumerable<int> ids = new int[] { 1, 2 };

            var model = ids.Select((q) => new CustomClass
            {
                ParentId = parentId,
                Id = q
            });

this works:

            int parentId = 1;
            IEnumerable<int> ids = new int[] { 1, 2 };

            var model = ids.Select((q) => new CustomClass
            {
                ParentId = parentId,
                Id = q
            }).ToArray();

Is there a way to change the AuditService class or SetProperty in a way that work with both types (array and System.Linq.Enumerable)?





Aucun commentaire:

Enregistrer un commentaire