DEV Community

loading...

How to get the actual table name from DbSet in EntityFramework Core 2.0.

jsakamoto
Microsoft MVP for Visual Studio and Development Tech. (prefer C#, .NET Core, ASP.NET Core, Azure Web Apps, TypeScript, and Blazor WebAssembly App!)
・2 min read

The way of getting actual table name

For example, if you have DbContext object like this (C#):

public class MyDbContext : DbContext {
    public DbSet<FooBar> FooBars { get; set; }
}
...

var dbContext = new MyDbContext();
Enter fullscreen mode Exit fullscreen mode

You can obtain the actual table name of the DbSet property from the DbContext instance with the following code.

// DbContext knows everything about the model.
var model = dbContext.Model;

// Get all the entity types information contained in the DbContext class, ...
var entityTypes = model.GetEntityTypes();

// ... and get one by entity type information of "FooBars" DbSet property.
var entityTypeOfFooBar = entityTypes.First(t => t.ClrType == typeof(FooBar));

// The entity type information has the actual table name as an annotation!
var tableNameAnnotation = entityTypeOfFooBar.GetAnnotation("Relational:TableName");
var tableNameOfFooBarSet = tableNameAnnotation.Value.ToString();

Enter fullscreen mode Exit fullscreen mode

Package as an extension method

By the way, we can get a DbContext from a DbSet.

See also: "How to get a DbContext from a DbSet in EntityFramework Core 2.0."

Therefore, you can package the above code as an extension method like this C# code:

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;

// Prerequire: You have to install DbContextGetter class in this project.
// https://dev.to/j_sakamoto/how-to-get-a-dbcontext-from-a-dbset-in-entityframework-core-c6m

public static class TableNameOfDbSetGetter
{
  public static string GetTableName<T>(this DbSet<T> dbSet) where T: class
  {
    var dbContext = dbSet.GetDbContext();

    var model = dbContext.Model;
    var entityTypes = model.GetEntityTypes();
    var entityType = entityTypes.First(t => t.ClrType == typeof(T));
    var tableNameAnnotation = entityType.GetAnnotation("Relational:TableName");
    var tableName = tableNameAnnotation.Value.ToString();
    return tableName;
  }
}

// How to use:
// 
// class MyDbContext : DbContext {
//    public DbSet<FooBar> FooBars { get; set; }
// }
// ...
// var myContext = new MyDbContext();
// var tableName = myContext.FooBars.GetTableName();
//                                  ~~~~~~~~~~~~~~
// tableName; // -> "FooBars"
Enter fullscreen mode Exit fullscreen mode

This code works fine even if the entity class is decorated with [TableAttribute("TableName")].

Happy coding :)

Discussion (1)

Collapse
bastijan profile image
Sasa Jovanovic

Actually, you already know a table name :)

// var tableName = myContext.FooBars.GetTableName();
// ~~~~~~~~~~~~~~
// tableName; // -> "FooBars"