How do you get the entity schema name using Code First (Entity Framework) and DbContext?

Our database has been designed in such a way that there are various schemes for production and various equivalent schemes for testing. For example, many tables are stored in the MyProduction schema, while the same tables are stored in the MyTest schema.

What I want to do is determine which schema is used by the table, so I know which one needs to be changed to it. Thus, by default, everything will be within the framework of production schemes. In the OnModelCreating event for DbContext, if I need to point to a test (defined using some true / false configuration), I need to determine the production scheme used, and then point to the test equivalent.

I already know how to install the circuit, but I cannot find how to get it. Any ideas how I can determine the schema the table uses?

Thanks.

+4
source share
3 answers

Try entering the code after the change according to your local settings:

var context = new YouDbContext("ConnectionName"); var adapter = (IObjectContextAdapter)context; var objectContext = adapter.ObjectContext; EntitySetBase schema = null; if (objectContext.MetadataWorkspace != null) { schema = objectContext.MetadataWorkspace .GetItems<EntityContainer>(DataSpace.SSpace).First() .BaseEntitySets .First(meta => meta.ElementType.Name == "ClassNameUnderYourDbContext"); } //See the properties of schema in debug mode to understand details 
0
source

Entity Framework schemas are System.ComponentModel.DataAnnotations.TableAttribute objects. The following are some methods that you can use to get the schema name and table name. Hooray!

  private string GetTableName(Type type) { var tableAttribute = type.GetCustomAttributes(false).OfType<System.ComponentModel.DataAnnotations.TableAttribute>().FirstOrDefault(); if (tableAttribute != null && !string.IsNullOrEmpty(tableAttribute.Name)) { return tableAttribute.Name; } else { return string.Empty; } } private string GetTableSchema(Type type) { var tableAttribute = type.GetCustomAttributes(false).OfType<System.ComponentModel.DataAnnotations.TableAttribute>().FirstOrDefault(); if (tableAttribute != null && !string.IsNullOrEmpty(tableAttribute.Schema)) { return tableAttribute.Schema; } else { return string.Empty; } } 
-one
source
 System.ComponentModel.DataAnnotations.Schema.TableAttribute 
-one
source

Source: https://habr.com/ru/post/1398258/


All Articles