In some reason, I need to use SQL in EFCore, and I will use table name of mapped entity. How can I get it?
Accepted Answer. You can get DbSet from DbContext by Type using the method DbContext. Set(Type entityType) . So if you have the model class name as string you should do some mapping to actual clr type.
The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.
Using the Microsoft.EntityFrameworkCore.Relational package in 2.X:
var mapping = dbContext.Model.FindEntityType(typeof(YourEntity)).Relational(); var schema = mapping.Schema; var tableName = mapping.TableName;
This assumes that dbContext
is a instance of class that inherits from DbContext
and that you have YourEntity
configured there.
Note that in EF Core 3.X, [.Relational()
provider extensions have been replaced] (https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#provider) with getters and so you can now access the schema as follows:
var entityType = dbContext.Model.FindEntityType(typeof(YourEntity)); var schema = entityType.GetSchema(); var tableName = entityType.GetTableName();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With