我怎样才能获得数据库表实体框架6的所有属性和属性显示名称?

时间:2017-11-10 08:44:09

标签: c# entity-framework entity-framework-6

例如我有类似的模型类:namespace DomainModelLayer

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

    }

并在 db Context 设置文章表

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

在Generic Repository中我需要获取 _t 属性和名称(例如:标题,عنوان),不需要pkey和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)
                .ToArray();
        }
    }
   }
上面的

不起作用,我不知道获取属性和名称。 并给我一个错误

  

找不到类型或命名空间名称'_t'(你错过了吗?   使用指令或程序集引用?)

2 个答案:

答案 0 :(得分:2)

typeof(x)无法使用变量typeof(T),如果要获取变量的类型,则必须使用_t.GetType(),但在您的情况下,将返回IDbSet<T>的类型1}}而不仅仅是T所以只需使用T

要获得Display Attribute,您必须使用以下内容:

public virtual string[] GetAllDisplayNames()
{
    return typeof(T).GetProperties().Select(property => ((DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault())?.Name).ToArray();
}

答案 1 :(得分:1)

获取使用typeof(T)_t.GetType()的类型 然后在那个

上使用方法GetProperties()