Search code examples
c#entity-frameworkforeign-keyscode-generationpoco

Reverse POCO Generator: How to Rename a Reverse Foreign Key?


I am using Simon Hughes' Entity-Framework Reverse POCO Generator to generate code-first EF classes for my Sql Server database. The generator is highly configurable and I am well-aware of how to rename the foreign-key column on the many-to-one side of the relationship. I cannot figure out how to make the generator rename the reverse relationship.

For example, I have a table named Product_User with a column named User_Info_ID that references table USER_INFO. When I run the generator, the one-to-many relationship in the User class is defined as follows:

    /// <summary>
    /// Child ProductUsers where [Product_User].[User_Info_ID] point to this entity (FK_PRODUCT_USER_User)
    /// </summary>
    public virtual System.Collections.Generic.ICollection<ProductUser> User1 { get; set; } // Product_User.FK_PRODUCT_USER_User

How do I get it to generate this instead?

    public virtual System.Collections.Generic.ICollection<ProductUser> UserProducts { get; set; } 

Solution

  • Inside the *.tt file's

    Settings.ForeignKeyName = (tableName, foreignKey, foreignKeyName, relationship, attempt) => {
    
        if (foreignKey.PkTableName == "USER_INFO" && foreignKey.FkTableName == "Product_User" 
            && foreignKey.FkColumn == "User_Info_ID" && relationship == Relationship.OneToMany)
            return "UserProducts";
    
    }
    

    The properties of the foreignKey parameter have the values that appear in the database schema, not the camel-case friendly output of the generator. I found this out the hard way by setting a breakpoint inside the *.tt file and invoking [Debug T4 Template] by right-clicking the *.tt file in the VS.NET Solution Explorer.