Remove virtual properties from TypeDescriptor.GetProperties ()

1

I've done a question of how to use SQLBulkCopy, the user @VirgilioNovic showed me a code that uses reflection to be able to save any type of list, however I do TypeDescriptor.GetProperties() it brings the properties collection and virtual , that would be connection, thus generating an error when trying to save in baco .

I was able to remove the IEnumerable using this code:

var properties = TypeDescriptor.GetProperties(typeof(T))
                .Cast<PropertyDescriptor>()
                .Where(l=> l.PropertyType == typeof(string) ||   
                   !typeof(IEnumerable).IsAssignableFrom(l.PropertyType));

But I could not remove the virtual classes, this and my class:

public class MensagemUnidade
{
        public int MensagemUnidadeId { get; set; }

        public string Titulo { get; set; }

        public string Texto { get; set; }

        public ICollection<FotoMensagemUnidade> Fotos { get; set; }

        public int UnidadeId { get; set; }

        public int ClienteId { get; set; }

        public virtual Cliente Cliente { get; set; }

        public virtual Unidade Unidade { get; set; }
}

In case I already managed to remove Fotos , but I needed to remove Cliente and Unidade , leaving only ClienteId and UnidadeId , if anyone knows a good way to do it would be grateful. >

EDIT: Adding properties to DataTable

foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType)
                                         ?? prop.PropertyType);
    
asked by anonymous 22.09.2017 / 13:48

1 answer

2

Try this:

  var properties = typeof(T).GetProperties()
                .Where(l=> l.PropertyType == typeof(string) ||
                            !typeof(IEnumerable).IsAssignableFrom(l.PropertyType) &&
                            (!l.GetMethod.IsVirtual));

Just switch PropertyDescriptor to PropertyInfo on foreach and use Type instead of TypeDescriptor - (typeof(T)) .

    
22.09.2017 / 13:52