This T4 assumes your
DbContext
is called
ApplicationDbContext
in a file called ApplicationDbContext.cs
and does not account for whatever custom namespaces need to be imported for this file for your use. It is set up for DI, but lacks consumption of an
IRepository
pattern or anything similar. It also expects to be in a directory below the
EnvDteHelper.ttinclude
.
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data.Entity.Design" #>
<#@ import namespace="System.Globalization" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Data.Entity.Design.PluralizationServices" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<# DTE Dte;#>
<#@ include file="../EnvDteHelper.ttinclude"#>
<#
var suggestedNs=System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint");
var projects = RecurseSolutionProjects(Dte);
var q= from p in projects
from pi in p.ProjectItems.Cast<ProjectItem>()
where pi.FileCodeModel!=null
select new{p,pi,CodeElements=pi.FileCodeModel.CodeElements.Cast<CodeElement>()};
var context= q.Where(x=>x.pi.Name=="ApplicationDbContext.cs").First();
var typesToMap = Descendants(context.CodeElements,ce=>ce.Children.Cast<CodeElement>()).OfType<CodeProperty>();
var project=GetProjectContainingT4File(Dte,false);
var pluralizationService = PluralizationService.CreateService(new CultureInfo("en-US"));
#>
using System.Linq;
using System.Web.Http.OData;
using Microsoft.AspNet.Identity.EntityFramework;
namespace <#=suggestedNs#>
{
<# foreach(var tm in typesToMap){
var singular=pluralizationService.Singularize(tm.Name);
var plural=pluralizationService.Pluralize(tm.Name);
#>
public class <#=tm.Name#>Controller : ODataController
{
readonly ApplicationIdentityContext _db;
public <#=tm.Name#>Controller(ApplicationIdentityContext db)
{
_db = db;
}
/// GET api/<#=singular#>
public IQueryable<<#=singular#>> Get()
{
return _db.<#=plural#>;
}
// GET api/<#=singular#>/5
public <#=singular#> Get(int id)
{
return _db.<#=plural#>.FirstOrDefault(x=>x.<#=singular#>Id==id);
}
}
<#}#>
}