为 DbContext 中的每个 DbSet 准备一个字段列表和显示名称

Prepare a List of fields and displaynames for each DbSet in DbContext

在我的项目(MVC5、EF6、.Net4.8)中,我需要准备一个文档,其中包含所有字段名称及其显示名称的列表。 例如,我的 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.PropertyType.GetGenericArguments()
        .Single()
        .GetProperties()
        .Select(prop => new [] { prop.DeclaringType.Name, prop.Name, prop.GetCustomAttribute<DisplayAttribute>()?.Name }))
    .ToList();

这首先遍历 YourContext 的所有属性,过滤掉 DbSet<> 类型的属性,然后遍历 generic 的属性每个 DbSet<> 的类型,并按照您要求的格式选择一个扁平的数组列表。