DEV Community

jsakamoto
jsakamoto

Posted on

6 1

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

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 :)

Image of AssemblyAI tool

Transforming Interviews into Publishable Stories with AssemblyAI

Insightview is a modern web application that streamlines the interview workflow for journalists. By leveraging AssemblyAI's LeMUR and Universal-2 technology, it transforms raw interview recordings into structured, actionable content, dramatically reducing the time from recording to publication.

Key Features:
🎥 Audio/video file upload with real-time preview
🗣️ Advanced transcription with speaker identification
⭐ Automatic highlight extraction of key moments
✍️ AI-powered article draft generation
📤 Export interview's subtitles in VTT format

Read full post

Top comments (1)

Collapse
 
bastijan profile image
Sasa Jovanovic

Actually, you already know a table name :)

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

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay