mardi 17 octobre 2017

Create instance of List using reflection c#

I work on method which will dynamically creates instances of collections in our entities. My problem is when I create new record which has to be inserted into database, my ICollection navigation properties are always null and in my safe method

I have to use something like this below to create new List and its definitely not good approach. If I dont create instance of List, Mapper will throw error that it cannot map Collection of something to null, for example it cannot map List of Categories to null.

Sample of my safe method

//check if record exists in database so i know if have to update or insert record (based on entity Id)
var entity = repository.GetById(detail.Id)
//....some code removed for brevity
if (entity.Categories == null)
{
    entity.Categories = new List<Category>();
}
if (entity.UserContacts == null)
{
    entity.UserContacts = new List<UserContact>();
}
//dto => entity
Mapper.PopulateEntity(dto, entity);
//update or insert later on.

Extension method which has to create instance of List<T> for example new List<Category>() like its shown above.

public TEntity InitializeEntity(TEntity entity)
    {
        var properties = entity.GetType().GetProperties();
        foreach (var prop in properties)
        {
            if (typeof(ICollection<TEntity>).Name == (prop.PropertyType.Name))
            {   
                var get = prop.GetGetMethod();
                //get assembly with entity namespace and class name
                var fullName = get.GetBaseDefinition().ReturnType.GenericTypeArguments[0].AssemblyQualifiedName;

                //create instance of object
                var myObj = Activator.CreateInstance(Type.GetType(fullName));

                //check if property is null or if get some value, dont want to rewrite values from database
                var value = prop.GetValue(entity);
                if (value == null)
                {
                    var listType = typeof(List<>);
                    var constructedListType = listType.MakeGenericType(myObj.GetType());
                    Activator.CreateInstance(constructedListType);
                }
            }
        }
        return entity;
    }

For some reason its not creating any instances at all and I cannot figure out where is problem.





Aucun commentaire:

Enregistrer un commentaire