简体   繁体   中英

Get DbSet name from class object type

I'm trying to get the DbSet name from the class object type. This is the definition of the DbSet in the DbContext:

public DbSet<User.Role> Roles { get; set; }

Now, from typeof(Role) I need the get the name of the DbSet "Roles".

There is any way to get this?

Is this what you are after?

public static void Main()
{
    var roleType = typeof(User.Role);

    var context = new FakeDbContext();

    var propertyInfo = GetDbSetProperty(roleType, context);

    Console.WriteLine(propertyInfo.Name);
}

public static PropertyInfo GetDbSetProperty(Type typeOfEntity, FakeDbContext context)
{
    var genericDbSetType = typeof(DbSet<>);
    // typeof(DbSet<User.Role>);
    var entityDbSetType = genericDbSetType.MakeGenericType(typeOfEntity);

    // DbContext type
    var contextType = context.GetType();

    return contextType
        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Where(p => p.PropertyType == entityDbSetType)
        .FirstOrDefault();      
}

public class FakeDbContext
{
    public DbSet<User.Role> Roles { get; set; }
}

public class DbSet<T>
{
}

public class User
{
    public class Role
    {
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM