Search code examples
t4pocolinq2db

Generating POCO classes with T4Model in linq2db for selected tables only


I am using linq2db as ORM for my web application project (ASP.NET Core 2.2) with SQL Server database.

The database consists of over 500 tables and only a subset of tables is relevant to the web application. Therefore, I'd like to only map the relevant tables using T4Model generation. Is there a way to generate the POCO class for specified tables only?

My current approach: generating POCO classes for all tables and then deleting the not needed ones.


Solution

  • Check this part of documentation https://github.com/linq2db/linq2db/tree/master/Source/LinqToDB.Templates#example-of-generation-process-customization

    You need to add this code to your T4 template to go through Tables dictionary and remove all tables you don't need, including associations to such tables and procedures that could return them. E.g.

    var allowedTables = new HashSet<string>() { "Patient", "Person"  };
    
    // go though Tables and remove all tables you don't need
    foreach (var kvp in Tables.ToList())
        if (!allowedTables.Contains(kvp.Value.TableName))
            Tables.Remove(kvp.Key); // remove table
        else
            // if table needed, check that it doesn't have associations to removed tables
            foreach (var keyKvp in kvp.Value.ForeignKeys.ToList())
                if (!allowedTables.Contains(keyKvp.Value.OtherTable.TableName))
                    kvp.Value.ForeignKeys.Remove(keyKvp.Key); // remove association to table
    
    // also remove all procedures that return filtered-out tables
    foreach (var kvp in Procedures.ToList())
        if (kvp.Value.ResultTable != null && !allowedTables.Contains(kvp.Value.ResultTable.TableName))
            Tables.Remove(kvp.Key); // remove procedure
    

    Unfortunatelly, it could still generate some leftovers, but you could filter them out in similar way.