Question

I am using the provided EF5.0 EntityGenerator T4 template. I am trying to figure out how to obtain the schema and table of each entity as the generator creates each class. My intention is to add two const properties to each class like so:

public class MyEntity {
    public const string TABLE = "MyEntityTable";
    public const string SCHEMA = "MyEntitySchema";
}

I can't figure out how to utilize what is in the T4 Template to modify to do this. Here is what I have so far (first line is already in the T4 Template):

<#=codeStringGenerator.EntityClassOpening(entity)#>
{
    public const string TABLE = "testTable";
    public const string SCHEMA = "testSchema";
<#

...and the T4 template continues. I want to replace "testTable" and "testSchema" with the appropriate information. Any help would be very much appreciated as T4 templates are not my forte.

Was it helpful?

Solution

I found this question: How to get the Schema name of a Table in Entity Framework? and built from there. My solution was to first create the extension methods in linked article and then modify the ObjectContext extension method to the following:

public static string GetTableAndSchema<T>(this ObjectContext context) where T : class
{
    var sql = context.CreateObjectSet<T>.ToTraceString();
    var startTrim = sql.LastIndexOf("FROM") + 5;
    var initialTrim = sql.SubString(startTrim);
    var endTrim = initialTrim.IndexOf("AS");

    return sql.Substring(startTrim, endTrim).Replace("[","").Replace("]","");
}

This then allowed me to put the following in my GenericRepository:

public GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : EntityBaseClass{
    //REMOVED IRRELEVANT CODE

    private MyContextType _context;

    public virtual void AddBulk<IEnumerable<TEntity> toAdd, string connectionString, int batchSize)
    {
        using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.TableLock | SqlBulkCopyOptions.CheckContstraints | SqlBulkCopyOptions.KeepIdentity))
        {
            sbc.DestinationTableName = _context.GetTableAndSchema<TEntity>();

            //DO THE REST OF SQL BULK COPY
        }
    }
}

This works perfectly for me and now allows me to have a SQL Bulk copy for every entity that exists in my context.

OTHER TIPS

See http://brewdawg.github.io/Tiraggo.Edmx/ you can install it via NuGet within Visual Studio and it serves up all of the metadata from your EDMX files that Microsoft hides from you, very simple, works great.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top