Remove virtual properties from Typedescriptor.Getproperties()

Asked

Viewed 40 times

2

I did a question how to use Sqlbulkcopy, the @Virgilionovic user showed me a code that uses Reflection to save any kind of list, but I do the TypeDescriptor.GetProperties() he brings the properties collection and virtual, that would be binding, thus generating an error when trying to save in Baco.

I managed to remove the IEnumerable using that code:

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

But I couldn’t 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 withdraw Fotos, but I had to take Cliente and Unidade , leaving only ClienteId and UnidadeId, if anyone knows a good way to do so would be grateful.

EDIT: Adding the properties to the DataTable

foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType)
                                         ?? prop.PropertyType);
  • 1

    But you need to use the TypeDescriptor and PropertyDescriptor?

  • I was seeing the difference between them Type and Typedescriptor, I’m only using because that’s how Victor passed me the other question, as I have little knowledge yet I haven’t changed, I’m studying.

1 answer

3


Try it like this:

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

Just swap PropertyDescriptor for PropertyInfo in the foreach and use Type instead of TypeDescriptor - (typeof(T)).

  • I had been trying so, but says that Propertydescriptor does not have a Getmethod(),as I have little experience with reflexions I do not know how to use properly.

  • I had not noticed, I thought if it is a Propertyinfo, I will change

  • 1

    When I tried to make the foreach that is in Edit he gave error saying that the object was null, but after the LINQ comment I switched to Type and it worked perfectly, I will study the difference between these properties, I wanted to know why with Typedescriptor I generated error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.