Search code examples
c#entity-frameworklinqentity-framework-6entity-framework-4

How to get a value of a property


Hello people i'm with the next problem:

public class Document
{
    public Header Header {get;set;}
    public Footer Footer{get;set;}
    public string Text{get;set;}
    public string Description{get;set;}
    public int NumberOfPages{get;set;}
}
public class Header
{
    public int Id{get;set;}
    public string Text{get;set;}
}
public class Footer
{
    public int Id{get;set;}
    public string Text{get;set;}
}

Imagine i have this domain, i will like to copy all the primitive properties of Document and the ones that aren't primitive, such as Header and Footer i would like just the text.

I have the next code just to copy the properties which are primitive:

public static List<DataPropertyReport> GetPrimitiveProperties<T>(T entity)
{
    var properties = entity.GetType().GetProperties();    
    List<DataPropertyReport> info = new List<DataPropertyReport>();

    foreach (var property in properties)
    {
        Object value = property.GetValue(entity, null);
        Type type = value != null ? value.GetType() : null;

        if (type != null && 
               (type.IsPrimitive || 
                type == typeof(string) || 
                type.Name == "DateTime"))
        {
            var name = property.Name;
            info.Add(new DataPropertyReport(name, value.ToString(), 1));
        }
    }    
    return info;
}

Solution

  • You could override ToString() on the non-primitive types and just call that overload:

    public class Header
    {
        public int Id { get; set; }
        public string Text { get; set; }
    
        public override string ToString()
        {
            return Text;
        }
    }
    public class Footer
    {
        public int Id { get; set; }
        public string Text { get; set; }
    
        public override string ToString()
        {
            return Text;
        }
    }