69

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.

GalacticCowboy
  • 11,663
  • 2
  • 41
  • 66

1 Answers1

100

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.

GarethJ
  • 6,496
  • 32
  • 42
GalacticCowboy
  • 11,663
  • 2
  • 41
  • 66
  • I had to use <#@ assembly name="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" #> to get the 3.5 version of System.Core.dll. – Lance Fisher Apr 02 '09 at 22:16
  • By chance, was the "containing" project a 2.0/3.0 project? That may explain why it didn't know how to find System.Core without the fully-qualified name. – GalacticCowboy Apr 09 '09 at 17:26
  • This worked for me after I changed the language from `C#` to `C#v3.5`. Thanks! Weird how the intellisense didn't show this as an option! – Dan Atkinson Feb 19 '10 at 16:35
  • @user1007074 And your point is? This question dates back to the private beta (or possibly the first public beta). I'm sure if you look hard enough you'll find *lots* of "interesting" stuff to comment on from that era. – GalacticCowboy Aug 20 '18 at 13:23