How to get the actual table name from DbSet in EntityFramework Core 2.0.
jsakamoto
Posted on December 28, 2017
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();
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();
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"
This code works fine even if the entity class is decorated with [TableAttribute("TableName")]
.
Happy coding :)
💖 💪 🙅 🚩
jsakamoto
Posted on December 28, 2017
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.