JN
less than a minute read

Getting schema information from an edmx file with POCO

#entity-framework#edmx#poco#t4-template#csharp

In this example I have two tables in my database, Customer and Company. Customer belongs to the dbo schema whereas Company belongs to the 'other' schema. By default the edmx file does not offer up information about the schema of the original tables however this is something that is stored in the underlying xml.

xml schema

To retrieve this information we need to edit our tt template.

NOTE: I'd recommend getting tangible T4 Editor when working with .tt files as it provides syntax highlighting and intellisense which makes working with these file much easier.

At the top of our tt template (after the input file has been declared) we need to create a new store item collection that will grab the schema information using the code below.

StoreItemCollection sic;
loader.TryCreateStoreItemCollection(inputFile, out sic);
EntityContainer sicEntityContainer = sic.GetItems().FirstOrDefault();

Then from within the foreach (EntityType entity in ItemCollection.GetItems()...) loop you can get the current schema name with the following:

string schemaName = "Unknown";
if (sicEntityContainer != null)
{
    EntitySet eset = sicEntityContainer.GetEntitySetByName(code.Escape(entity), true);
    schemaName = eset.MetadataProperties["Schema"].Value.ToString();
}

Now we have the schema name we can do what we like with it. You might want to add a readonly property by adding the following just after the class is created.

public string Schema
{
    get { return "<#= schemaName #>"; }
}

With these small changes our auto generated classes now look like this:

Code comparison

Hope this helps


Leave a comment