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 $"{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 ?
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 $"{schema ?? "(unknown)"}.{entityType.GetTableName()}";
}
}
Example
using var context = new YourContext();
Console.WriteLine(context.GetTableNameWithScheme<YourModel>());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.