Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Linq in a T4 template?

Tags:

linq

t4

I am using T4 to generate some screens and middle-tier code for a project, and would like to use Linq to simplify some of my template code. However, when I try to use Linq, the template reports a syntax error.

like image 411
GalacticCowboy Avatar asked Oct 29 '08 14:10

GalacticCowboy


People also ask

What can I use LINQ for?

LINQ that stands for Language Integrated Query (pronounced as “link”) is a . NET language extension that supports data retrieval from different data sources like XML document, databases and collections. It was introduced in the . NET 3.5 framework.

Does Mono support LINQ?

Yes. Right click on your project, select 'Options'->'Runtime' and select '2.0' from the drop-down list.


1 Answers

By default in Visual Studio 2008 (and as used in most online examples) the template is compiled with the 2.0 Framework, which does not include Linq. (See MSDN forum thread)

To solve the problem, three steps are needed:

  1. In your template's language attribute, specify "C#v3.5" or "VBv3.5" - this step is not required for VS2010, where .Net 4.0 is always used.
  2. Add an assembly directive for System.Core.dll
  3. Import the System.Linq namespace

Your template will now look something like this:

<#@ template language="C#v3.5" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> 

You can now use Linq and other new language features in your template.

like image 78
GalacticCowboy Avatar answered Oct 01 '22 23:10

GalacticCowboy