Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get database table name with schema name from entity programmatically [duplicate]

I'm trying to get the SQL table name for the entity. When I work with the MetadataWorkspace queries I get lots of information from the object or the storage space. But schema name and table name are not present.

I try query all the EntityType objects for CSpace and SSpace and I can see both listed correctly but I can't figure out how to get SSpace from CSpace.

So say I have a type in the object model called User - how do I find the tablename with schema name (tkp.User) in the database?

Is there any way to do this?

like image 281
PaulP Avatar asked Mar 24 '23 08:03

PaulP


1 Answers

There is no perfect answer to this, but this should work...

var ssSpaceSet = objectContext.MetadataWorkspace
    .GetItems<EntityContainer>(DataSpace.SSpace).First()
    .BaseEntitySets
    .First(meta => meta.ElementType.Name == "YourEntityName");

If you look up in debugger, Table property should have the real table name.

You'd need to use reflection in the last part.
Good news is it should transparently work with EF6 too (as it has a similar base class)

(it's similar for schema, should be in there also - this is the space for Db/SQL mapped names, facets etc.)

See this post of mine with many details
Get Model schema to programmatically create database using a provider that doesn't support CreateDatabase


Get Model schema to programmatically create database using a provider that doesn't support CreateDatabase
How I can read EF DbContext metadata programmatically?
How check by unit test that properties mark as computed in ORM model?
Programmatic data transformation in EF5 Code First migration
Entity Framework MigrationSqlGenerator for SQLite
http://entityframework.codeplex.com/
Entity Framework - Get Table name from the Entity
ef code first: get entity table name without dataannotations
Get Database Table Name from Entity Framework MetaData
http://www.codeproject.com/Articles/350135/Entity-Framework-Get-mapped-table-name-from-an-ent
like image 95
NSGaga-mostly-inactive Avatar answered Apr 16 '23 16:04

NSGaga-mostly-inactive