how can i get all properties and attribute display name of database table entity framework 6?

c# entity-framework entity-framework-6


for example i have model class like that :namespace DomainModelLayer

   public class Article:BaseModel
        // id in base model long Id;
        [Display(Name = "عنوان")]
        public string Title { get; set; }
        [Display(Name = "محتوا")]
        public string Content { get; set; }
        [Display(Name = "تاریخ مطلب")]
        public DateTime InsertDate { get; set; }
        [Display(Name = "دسته مطلب")]
        public long ArticleCategoryId { get; set; }
        public ArticleCategory ArticleCategory { get; set; }


and in db Context set articles table

     public virtual DbSet<Article> Articles { get; set; }

in Generic Repository i need get _t properties and name (ex: Title , عنوان ), no need to pkey and fkey.

  public abstract class BaseRepository<T> : IBaseRepository<T> where T : BaseModel
      private readonly IDbSet<T> _t;
        private readonly IUnitOfWork _unitOfWork;
        private IQueryable<T> _db;
        protected BaseRepository(IUnitOfWork unitOfWork)
            _unitOfWork = unitOfWork;
            _t = _unitOfWork.Set<T>();
             _db = _t;

      public virtual string[] GetAllNameOfDbfileds()
            return typeof(_t).GetProperties()
                .Select(property => property.Name)

above doesn't work , i no have idea for get properties and names . and get me an error

The type or namespace name '_t' could not be found (are you missing a using directive or an assembly reference?)

11/10/2017 8:44:09 AM

Accepted Answer

typeof(x) doesnt work with variables use typeof(T), if you want to get the Type of a variable you have to use _t.GetType() but in your case that would return the Type of IDbSet<T> instead of only T so just simply use T.

To get the Display Attribute you have to use the following:

public virtual string[] GetAllDisplayNames()
    return typeof(T).GetProperties().Select(property => ((DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault())?.Name).ToArray();
11/10/2017 9:13:16 AM

Popular Answer

to get type use typeof(T) or _t.GetType() and then use method GetProperties() on that

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow