Getproperties() except Notmapped

Asked

Viewed 55 times

1

I have a method that searches all the properties of my model, but I would not like to bring the entities that have as DataAnnotation the attribute NotMapped.

Method

private IEnumerable<string> GetColumns()
{
    return typeof(T)
            .GetProperties()
            .Where(e => e.Name != "Id" && !e.PropertyType.GetTypeInfo().IsGenericType)
            .Select(e => e.Name);
}

Model:

using LaioMVC.Core.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace LaioMVC.Core.Models
{
    public class Usuario : EntityBase
    {
        [Required]
        public string Nome { get; set; }

        [Required]
        public string Login { get; set; }

        [Required]
        public string Password { get; set; }

        [NotMapped]
        [Required]
        public string ConfirmPassword { get; set; }
    }
}

1 answer

1


Since it was not posted all of the class I did without being generic, but the issue there is to filter by attribute then it would be this:

using System;
using static System.Console;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;

public class Program {
    public static void Main() {
        foreach (var c in GetColumns()) WriteLine(c);
    }
    private static IEnumerable<string> GetColumns() => typeof(Usuario).GetProperties()
            .Where(e => e.Name != "Id" && !(Attribute.GetCustomAttribute(e, typeof(NotMappedAttribute)) is NotMappedAttribute))
            .Select(e => e.Name);
}

public class Usuario {
    [Required]
    public string Nome { get; set; }

    [Required]
    public string Login { get; set; }

    [Required]
    public string Password { get; set; }

    [NotMapped]
    [Required]
    public string ConfirmPassword { get; set; }
}

Behold working in the .NET Fiddle.Also put on the Github for future reference.

Browser other questions tagged

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