![](/img/trans.png)
[英]How can I get column properties of DB table in entity framework (database first approach)
[英]how can i get all properties and attribute display name of database table 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; }
}
並在數據庫上下文中設置文章表
public virtual DbSet<Article> Articles { get; set; }
在通用存儲庫中,我需要獲取_t屬性和名稱(例如:Title,عنوان),不需要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”(是否缺少using指令或程序集引用?)
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();
}
要獲取類型,請使用typeof(T)
或_t.GetType()
,然后在該類型上使用方法GetProperties()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.