Search code examples
entity-frameworkdomain-driven-designentity-framework-5n-layer

EF5 Database first model templates (tt) for class generation


I want to make that all my Entities created form an existing database inherits from the same interface.

I suppose this can be done through the templates. And I've seen that ugly .tt file, but there is no help (or I haven't found it).

There are any documentation, examples, ... of the templates?

There are any tips or pre-made templates for common paradigms, for example N-Layer Design or Domain Driven Desing?


Solution

  • Look for "T4 Templates". That will give you introduction to T4 Templates (.tt files). With a bit of searching you can easily extend this template to your needings. I did this myself already, but with a template from EF4. I don't know if the templates differ.

    I made a little helper functions for this:

    string Interfaces(EntityType entity)
    {
        string interfaces = string.Empty;
    
        if (entity.Members.OfType<EdmProperty>().Any(edmProperty => edmProperty.Name == "Guid" && ((PrimitiveType)edmProperty.TypeUsage.EdmType).PrimitiveTypeKind == PrimitiveTypeKind.Guid))
        {
            interfaces += ", IHasWritableGuid";
        }
    
        return interfaces;
    }
    

    The part where the template writes the actually entity class (this differs for sure in the new template) is somewhat below "Write EntityType classes." in the EF4 template.

    <#=Accessibility.ForType(entity)#>
    <#=code.SpaceAfter(code.AbstractOption(entity))#>
    partial class
    <#=code.Escape(entity)#> :
    <#=BaseTypeName(entity, code)#>
    <#= Interfaces(entity) #>
    

    Here I just added a call to my interfaces method.

    I know this is not the exact answer, but it should give you help with editing the template file yourself. Just bite yourself through it. :)