在我的项目(MVC5,EF6,.Net4.8)中,我需要准备一个文档,其中包含所有字段名称及其DisplayName的列表。例如,我的DbContext中具有以下类:
public class Teacher
{
[Key]
public int Id { get; set; }
[Display(Name = "First name of the teacher")]
public string FirstName { get; set; }
[Display(Name = "Last name of the teacher")]
public string LastName { get; set; }
[Display(Name = "Phone number of the teacher")]
public string Phone { get; set; }
}
public class Student
{
[Key]
public int Id { get; set; }
[Display(Name = "First name of the student")]
public string FirstName { get; set; }
[Display(Name = "Last name of the student")]
public string LastName { get; set; }
[Display(Name = "Birthdate of the student")]
public DateTime Birthdate { get; set; }
}
而且我需要每个字段名称及其对应的DisplayName的列表,如下所示:
["Teacher", "Id", null]
["Teacher", "FirstName", "First name of the teacher"]
["Teacher", "LastName", "Last name of the teacher"]
["Teacher", "Phone", "Phone number of the teacher"]
["Student", "Id", null]
["Student", "FirstName", "First name of the student"]
["Student", "LastName", "Last name of the student"]
["Student", "Birthdate", "Birthdate of the student"]
是否可以自动创建这样的列表?
您可以使用反射:
typeof(YourContext)
.GetProperties()
.Where(prop => prop.PropertyType.IsGenericType
&& prop.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
.SelectMany(dbSet => dbSet.GetGenericArguments()
.Single()
.GetProperties()
.Select(prop => new [] { prop.DeclaringType.Name, prop.Name, prop.GetCustomAttribute<DisplayAttribute>()?.Name }))
.ToList();
您可以使用Reflection获得预期的结果:
private static List<List<string>> GetMembers(Type type)
{
return type.GetProperties()
.Select(x => new List<string>
{
type.Name,
x.Name,
(x.GetCustomAttribute(typeof(DisplayAttribute)) is DisplayAttribute displayAttribute) ? displayAttribute.Name : null
})
.ToList();
}
测试
List<List<string>> mebmers = GetMembers(typeof(Teacher));
结果:
foreach(var item in mebmers)
{
Console.WriteLine(string.Join(",", item));
}
我希望能帮到您。