【问题标题】:Get DbSet name from class object type从类对象类型中获取 DbSet 名称
【发布时间】:2017-04-25 21:49:10
【问题描述】:

我正在尝试从类对象类型中获取 DbSet 名称。这是DbContext中DbSet的定义:

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

现在,我需要从 typeof(Role) 获取 DbSet“角色”的名称。

有什么办法可以得到这个?

【问题讨论】:

  • 我有几个问题:您使用的是Entity Framework 6吗?,您需要在DbContext中找到名为RolesProperty,还是只是DbSet&lt;User.Role&gt;的类型?跨度>
  • 嗨安德烈斯。是的!我正在使用 EF6。我只需要在字符串中获取名称“角色”就可以了。来自 typeof(Role)

标签: c# asp.net entity-framework


【解决方案1】:

这就是你所追求的吗?

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
    {
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-24
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    相关资源
    最近更新 更多