0

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;
Smudge202
  • 4,689
  • 2
  • 26
  • 44

1 Answers1

2

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

Community
  • 1
  • 1
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
  • Thanks Dennis. I didn't expect it to be overly easy, the methods used on that discussion to get the table name don't look too performance friendly, which would likely lead to optimisations to store the metadata somewhere, which in turn makes it unworthwhile - why not just store the metadata at design time. As such, any recommendations on how to store the data? Attributes via T4 or are there better approaches? Thanks again! – Smudge202 Dec 09 '11 at 10:42
  • I can't think of any better approaches either, sorry. – Dennis Traub Dec 09 '11 at 10:44