Это упрощенная версия проекта, которую вам нужно написать для генерации предыдущего кода.Прежде всего создайте каталог, куда и пойдут любые будущие сущности.Для простоты я вызвал каталог Entities и создал файл с именем User.cs, который содержит исходный код для класса User.
Для каждого из этих шаблонов создайте файл .tt, начинающийся с имени объекта, за которым следует имя функции.Таким образом, файл tt для пользовательской модели будет называться UserModel.tt, в который вы помещаете шаблон модели.Для пользовательского контроллера - USerController.tt, в который вы поместите шаблон контроллера.Там будет только файл Autopper, и универсальный репозиторий пользователя будет называться UserGenericRepository.tt, в который (как вы уже догадались) вы поместите шаблон универсального репозитория
Шаблон для модели
<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<#
var hostFile = this.Host.TemplateFile;
var entityName = System.IO.Path.GetFileNameWithoutExtension(hostFile).Replace("Model","");
var directoryName = System.IO.Path.GetDirectoryName(hostFile);
var fileName = directoryName + "\\Entities\\" + entityName + ".cs";
#>
<#= System.IO.File.ReadAllText(fileName).Replace("public class " + entityName,"public class " + entityName + "Model") #>
Я заметил, что исходный файл не имеет пространств имен или использования, поэтому файл UserModel не будет компилироваться без добавления использования в файл User.cs, однако файл генерируется согласно спецификации
Шаблон для контроллера
<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<#
var hostFile = this.Host.TemplateFile;
var entityName = System.IO.Path.GetFileNameWithoutExtension(hostFile).Replace("Controller","");
var directoryName = System.IO.Path.GetDirectoryName(hostFile);
var fileName = directoryName + "\\" + entityName + ".cs";
#>
/// <summary>
/// <#= entityName #> controller
/// </summary>
[Route("api/[controller]")]
public class <#= entityName #>Controller : Controller
{
private readonly LocalDBContext localDBContext;
private UnitOfWork unitOfWork;
/// <summary>
/// Constructor
/// </summary>
public <#= entityName #>Controller(LocalDBContext localDBContext)
{
this.localDBContext = localDBContext;
this.unitOfWork = new UnitOfWork(localDBContext);
}
/// <summary>
/// Get <#= Pascal(entityName) #> by Id
/// </summary>
[HttpGet("{id}")]
[Produces("application/json", Type = typeof(<#= entityName #>Model))]
public IActionResult GetById(int id)
{
var <#= Pascal(entityName) #> = unitOfWork.<#= entityName #>Repository.GetById(id);
if (<#= Pascal(entityName) #> == null)
{
return NotFound();
}
var res = AutoMapper.Mapper.Map<<#= entityName #>Model>(<#= Pascal(entityName) #>);
return Ok(res);
}
/// <summary>
/// Post an <#= Pascal(entityName) #>
/// </summary>
[HttpPost]
public IActionResult Post([FromBody]<#= entityName #>Model <#= Pascal(entityName) #>)
{
Usuario u = AutoMapper.Mapper.Map<<#= entityName #>>(<#= Pascal(entityName) #>);
var res = unitOfWork.<#= entityName #>Repository.Add(u);
if (res?.Id > 0)
{
return Ok(res);
}
return BadRequest();
}
/// <summary>
/// Edit an <#= Pascal(entityName) #>
/// </summary>
[HttpPut]
public IActionResult Put([FromBody]<#= entityName #>Model <#= Pascal(entityName) #>)
{
if (unitOfWork.<#= entityName #>Repository.GetById(<#= Pascal(entityName) #>.Id) == null)
{
return NotFound();
}
var u = AutoMapper.Mapper.Map<<#= entityName #>>(<#= Pascal(entityName) #>);
var res = unitOfWork.<#= entityName #>Repository.Update(u);
return Ok(res);
}
/// <summary>
/// Delete an <#= Pascal(entityName) #>
/// </summary>
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
if (unitOfWork.<#= entityName #>Repository.GetById(id) == null)
{
return NotFound();
}
unitOfWork.<#= entityName #>Repository.Delete(id);
return Ok();
}
}
<#+
public string Pascal(string input)
{
return input.ToCharArray()[0].ToString() + input.Substring(1);
}
#>
Шаблон для AutoMapper
<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<#
var directoryName = System.IO.Path.GetDirectoryName(this.Host.TemplateFile) + "\\Entities";
var files = System.IO.Directory.GetFiles(directoryName, "*.cs");
#>
public class AutoMapper
{
<#
foreach(var f in files)
{
var entityName = System.IO.Path.GetFileNameWithoutExtension(f);
#>
CreateMap<<#= entityName #>Model, <#= entityName #>>();
CreateMap<<#= entityName #>, <#= entityName #>Model>();
<#
}
#>}
Это в основном проходит через каждый файлв папке сущностей и создает сопоставления между сущностью и моделью сущности
Шаблон для универсального репозитория
<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<#
var hostFile = this.Host.TemplateFile;
var entityName = System.IO.Path.GetFileNameWithoutExtension(hostFile).Replace("GenericRepository","");
var directoryName = System.IO.Path.GetDirectoryName(hostFile);
var fileName = directoryName + "\\" + entityName + ".cs";
#>
public class GenericRepository
{
private GenericRepository<<#= entityName #>> <#= Pascal(entityName) #>Repository;
public GenericRepository<<#= entityName #>> UserRepository
{
get
{
if (this.<#= Pascal(entityName) #>Repository == null)
{
this.<#= Pascal(entityName) #>Repository = new GenericRepository<<#= entityName #>>(context);
}
return <#= Pascal(entityName) #>Repository;
}
}
}<#+
public string Pascal(string input)
{
return input.ToCharArray()[0].ToString() + input.Substring(1);
}
#>