Smudge202
Smudge202

Reputation: 4687

Retrieve Data Model definition for Entity at Runtime

In either (or all) EF Code-First, EF Model-First, or L2S, is it possible to determine, for example, the name of the originating database table - assuming a one-to-one mapping - given an Entity class, at runtime?

For example, if I have a database with a table called "People", which I've mapped through the aforementioned ORMs to my entity class "Person", is there a way given respective DataContexts and/or Entity class Type/Instance, to determine the original database table name; "People"?

Obviously, I could do this by adding the metadata to the entities; using a modified T4 Template or custom Attributes for example (similar to how I believe L2S stores the information on the context), but I'm wondering if I can do it out-of-the-box?

Thanks in advance!

EDIT: Ok, I think I've found how to do this in Linq 2 Sql, so the question only remains for EF.

// for L2S the Table Name can be retrieved as so...
object[] info = typeof(TSource).GetCustomAttributes(typeof(System.Data.Linq.Mapping.TableAttribute), true); 
String table = (info[0] as System.Data.Linq.Mapping.TableAttribute).Name; 

EDIT: I'm not sure which is better, but it seems you can also get the table name as follows. At a glance, I prefer this second approach, though I'd prefer it more if Mapping.GetTable was Generic - GetTable<TSource>()

// for L2S the Table Name can be retrieved via the Context's mapping as so:
string TableName = context.Mapping.GetTable(typeof(TSource)).TableName;

Upvotes: 0

Views: 809

Answers (1)

Dennis Traub
Dennis Traub

Reputation: 51654

The short answer concerning EF: No, it can't be easily done.

Extended discussion and possible workarounds: Get Database Table Name from Entity Framework MetaData

Upvotes: 2

Related Questions