Can I get the classes generated using T4 Templates to inherit from the same class

StackOverflow https://stackoverflow.com/questions/20728496

  •  20-09-2022
  •  | 
  •  

Question

I'm writing a small console app to generate some scaffolding code using the TextTemplatingFilePreprocessor.

I have a number of .tt files that are used and they all use the same Model from which the values are derived for the individual classes. Following along this MSDN article I have created another partial class file for the class being created and added a constructor that allows me to pass in the Model.

So, for a class to be generated called ServiceEntity, I have a ServiceEntity.tt file and a 2nd file called something like ServiceEntityCode.cs which contains something like this...

partial class ServiceEntity
{
    IServiceConfig _config;

    public ServiceEntity(IServiceConfig config)
    {
        _config = config;
    }
}

The thing is, I'm having to duplicate this code to create a constructor forr each class I'm generating.

I'd prefer to have something like...

class BaseTemplate
{
    IServiceConfig _config;

    public BaseTemplate(IServiceConfig config)
    {
        _config = config;
    }
}

partial class ServiceEntity : BaseTemplate
{
    public ServiceEntity() : base() {}
}

Can anyone give me a pointer to whether or not such a thing can be achieved and, if it can, where I might find details on how?

===EDIT=== Here's a sample template...

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>

using System.Runtime.Serialization;

namespace <#= _config.ServiceEntityNamespace #>
{
    [DataContract()]
    public class <#= _config.ServiceEntityName #> 
    {
        [DataMember()]
        public string Description { get; set; }

        [DataMember()]
        public int Id { get; set; }

        [DataMember()]
        public string Name { get; set; }
    }
}

The .cs code generated under the .tt file includes this ...

public partial class ServiceEntity : ServiceEntityBase
{
//...
}

But ServiceEntityBase itself doesn't inherit from anything.

Was it helpful?

Solution

Is this what you are after?

namespace <#= _config.ServiceEntityNamespace #>
{
    [DataContract()]
    public class <#= _config.ServiceEntityName #> : BaseTemplate
    {
        public <#= _config.ServiceEntityName #>() : base() {}

        [DataMember()]
        public string Description { get; set; }

        [DataMember()]
        public int Id { get; set; }

        [DataMember()]
        public string Name { get; set; }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top