代码之家  ›  专栏  ›  技术社区  ›  arman

如何获取数据库表实体框架6的所有属性和属性显示名称?

  •  -1
  • arman  · 技术社区  · 8 年前

    例如,我有这样的模型类: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; }
    
        }
    

    并且在 设置文章表

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

    在通用存储库中,我需要获取 _t

      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();
            }
        }
       }
    

    上面的操作不起作用,我不知道如何获取属性和名称。 给我一个错误

    找不到类型或命名空间名称“\u t”(是否缺少 使用指令或程序集引用?)

    2 回复  |  直到 8 年前
        1
  •  2
  •   Rand Random    8 年前

    typeof(x) 不适用于变量使用 typeof(T) ,如果要获取变量的类型,必须使用 _t.GetType() 但在你的情况下,这将返回 IDbSet<T> 而不仅仅是 T 所以只要简单地使用 T .

    获得 Display Attribute 您必须使用以下工具:

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

    typeof(T) _t.GetType() 然后使用方法 GetProperties() 在那上面