EF5如何从DBSET获取模式和表名称

发布于 2025-02-01 03:07:51 字数 495 浏览 5 评论 0原文

我想编写一个扩展程序,该扩展名应该从DBSET获取表名和模式。

public static string GetTableInfo<T>(this DbSet<T> dbSet) where T : class
{
    var tableName = ?? // how to retrieve if from the dbSet ? 
    var schemaName = ?? // how to retrieve if from the dbSet ? 

    return $"{schemaName}.{tableName}";
}

用法:

var tableInfo = _libraryContext.Books.GetTableInfo();
// tableInfo should return "dbo.Book"

如何直接从DBSET获取桌子和模式名称?

I want to write an extension that should get the table name and the schema from a dbSet.

public static string GetTableInfo<T>(this DbSet<T> dbSet) where T : class
{
    var tableName = ?? // how to retrieve if from the dbSet ? 
    var schemaName = ?? // how to retrieve if from the dbSet ? 

    return 
quot;{schemaName}.{tableName}";
}

Usage :

var tableInfo = _libraryContext.Books.GetTableInfo();
// tableInfo should return "dbo.Book"

how i can get the table and schema names directly from the DbSet ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

留蓝 2025-02-08 03:07:51

查看是否可以进行以下内容并适应您的代码,因为这是接近但不完全想要的。

在DBContext

modelBuilder.HasDefaultSchema("dbo");

扩展方法

public static class EntityHelpers
{
    public static string GetTableNameWithScheme<T>(this DbContext context) where T : class
    {
        var entityType = context.Model.FindEntityType(typeof(T));
        var schema = entityType.GetDefaultSchema();
        return $"{schema ?? "(unknown)"}.{entityType.GetTableName()}";
    }
}

示例中

using var context = new YourContext();
Console.WriteLine(context.GetTableNameWithScheme<YourModel>());

See if you can take the following and adapt to your code as this is close but not exactly what you wanted.

In the dbContext

modelBuilder.HasDefaultSchema("dbo");

Extension method

public static class EntityHelpers
{
    public static string GetTableNameWithScheme<T>(this DbContext context) where T : class
    {
        var entityType = context.Model.FindEntityType(typeof(T));
        var schema = entityType.GetDefaultSchema();
        return 
quot;{schema ?? "(unknown)"}.{entityType.GetTableName()}";
    }
}

Example

using var context = new YourContext();
Console.WriteLine(context.GetTableNameWithScheme<YourModel>());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文