问题
I would like to modify the T4 template that Entity Framework 6 (model-first) uses to generate types in order to inject a GeneratedCodeAttribute on all entity class definitions. I want this feature persisted any time I add a new ADO.NET Entity Data Model, in any project, in any solution - so I need to make the change in something other than the T4 template which gets generated with my entity diagram.
Could an EF6 expert advise how I would go about doing this?
This is what I've tried (without success): I located a T4 template called CSharpDbContext.Types.tt, the contents of which appear to be identical to the T4 template that gets generated with my .edmx file. I assume this file is the EF 6.x DbContext Generator that shows up in the Visual Studio Add New Item list. The file location of CSharpDbContext.Types.tt on my computer is:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ItemTemplates\CSharp\Data\1033\DbCtxCSEF6
When I modify this file, however, I get exactly the same class definition as I do before the modification. If I move it to an entirely different location, I again get the same result. From what I can tell, there is no connection between this file and my edmx-specific T4 template.
Appreciate if someone can shed some light on this.
回答1:
Step 1: Don't do that. Don't modify the template that's downloaded with EF because you won't be able to easily and consistently replicate that on a "clean" machine.
Step 2: Once you add EF DB-first you can edit the copy of the template inside your project. This template will be stored in code repository and you'll be able to get repeatable results without "magical" setup. The drawback is that you'll need to modify the template every time you create a new EF context.
To modify the template open MyEFItem.tt, study how it works and edit it as needed. In your case I'd search for "partial class" in that .tt and insert the [GeneratedCode] on the line before that. As soon as you save you'll see the changes in the generated .cs, or you can right-click on the .tt and "Run Custom Tool"
来源:https://stackoverflow.com/questions/29420672/modifying-entity-framework-types-t4-template