C # code generation Tool: Text template first experience class names that use T4 to bulk modify Entity Framework

Source: Internet
Author: User
Tags emit

Turn from: http://www.cnblogs.com/huangcong/archive/2011/07/20/1931107.html in the previous text template (T4) experience we already know the usefulness of T4, Here's a look at how you can use it to implement bulk modification of the class name in the Entity Framework. We all know that there is one way in the ADO Entity Data model to generate a data model from a database model, which is a very simple way to generate the Entity Data model. But because of the lack of custom interface provided by Microsoft, we can't implement batch modification of the generated data Model entity class (at least I've been searching the internet for a long time, I haven't found a way, which one knows please enlighten me, this bothers me for a long time, or which good man does have batch modification software, trouble sharing ha), Of course you can modify the table in the view environment of the edmx file, but this step is not only cumbersome, and when you modify the database schema, regenerate the Entity data frame, the previous manual modification will be all overwritten, so once the database is modified, it is the beginning of the nightmare. There has to be a flexible way to solve this, and I'm thinking of using the T4-based ADO-tracking entity generator to solve the problem. Here's how it's done. Demand Analysis:

The most recent system in the database schema table structure is more complex, there are dozens of tables, and some of the base table names are named Base_xxx (XXX as the table name), which led me to use the Entity Data model in the following way to do data manipulation:

Usercenterentities dataBase = new Usercenterentities ();
Get all Users
DataBase.Base_User.Select (U = u). ToList ();

As can be seen from the above, the Base_user table in the database is mapped to the Base_user class. But I want the class name of the Base_user table map to be userentity. That is, the code style looks like this:

Usercenterentities dataBase = new Usercenterentities ();
Get all Users
DataBase.UserEntity.Select (U = u). ToList ();

Of course, everyone has to say, this is difficult, the simplest way is to directly in the Entity Data Model View Editor to modify the table map name can be:

This method is feasible, but if I want to modify the dozens of tables, and once the database has been modified and have to be renamed all again, I think I will crash, therefore, it is necessary to find a suitable method, that is, using the T4-based ADO self-tracking entity generator. Let's see how it works.

1) database preparation for a simple demonstration, I'll just create a demo database of 2 tables, please run the SQL statement with your own database to generate a new database.Code2) Create Data Entity Framework Open VS2010, create a new console project, right-click on the project-new item--ado.net Entity Data Model:

Select "Generate From Database"--next--Create new connection--Add the TestDB database we just created--Next:

Select all of the database objects--complete, so that we have the original Entity Data model:

Open Model1.Designer.cs, you can see 2 entity class names are not what I want.

OK, let's see how to bulk Modify the entity class name, ADO. NET self-tracking entity generator is finally ready to go. Create an ADO-self-tracking entity generator. In the Entity Data Model attempt editor, right--Add code generator--Select the ADO self-tracking entity generator.

Once added, we can find 2 more templates in the project and synchronize the generated class files:

4) Modify the Model1.tt template to open the Model1.tt file and add the following code at the end of the file:Code


Then find the following code:

Emit entity type
foreach (EntityType entity in itemcollection.getitems<entitytype> (). (e = e.name))
{
Filemanager.startnewfile (entity. Name + ". cs");
Beginnamespace (namespacename, code);
Writeentitytypeserializationinfo (Entity, itemcollection, Code, EF);
#>
<#=accessibility.fortype (Entity) #> <#=code. SpaceAfter (code. Abstractoption (Entity) #>partial class <#=code. Escape (Entity) #><#=code. Stringbefore (":", code. Escape (entity. BaseType)) #><#=entity. BaseType = = null? ":": "," #>iobjectwithchangetracker, INotifyPropertyChanged
{
<#

Replace with the following code, and save:

Emit entity type
foreach (EntityType entity in itemcollection.getitems<entitytype> (). (e = e.name))
{
Filemanager.startnewfile (GetClassName (entity. Name, "Entity") + ". cs");
Beginnamespace (namespacename, code);
Writeentitytypeserializationinfo (Entity, itemcollection, Code, EF);
#>
<#=accessibility.fortype (Entity) #> <#=code. SpaceAfter (code. Abstractoption (Entity) #>partial class <#=getclassname (code. Escape (Entity), "entity") #><#=code. Stringbefore (":", code. Escape (entity. BaseType)) #><#=entity. BaseType = = null? ":": "," #>iobjectwithchangetracker, INotifyPropertyChanged
{
<#We can then see the file name of the project and the class name in bulk modified to the names we want:

5) Modify the Model1.Context.tt template to open the Model1.Context.tt file and add the following code at the end of the file:Code

Then find the following code:

<#
Region. Begin ("ObjectSet attribute", 2);

foreach (EntitySet EntitySet in container. Baseentitysets.oftype<entityset> ())
{
#>

<#=accessibility.forreadonlyproperty (EntitySet) #> Objectset<<#=code. Escape (Entityset.elementtype) #>> <#=code. Escape (EntitySet) #>
{
get {return <#=code. FieldName (EntitySet) #>?? (<#=code. FieldName (entitySet) #> = Createobjectset<<#=code. Escape (Entityset.elementtype) #>> ("<#=entitySet.Name#>")); }
}
Private Objectset<<#=code. Escape (Entityset.elementtype) #>> <#=code. FieldName (EntitySet) #>;
<#

Change to the following code, and save:

<#
Region. Begin ("ObjectSet attribute", 2);

foreach (EntitySet EntitySet in container. Baseentitysets.oftype<entityset> ())
{
String className = GetClassName (code. Escape (Entityset.elementtype), "Entity");
String entitysetelementtype = GetClassName (code. Escape (Entityset.elementtype), "Entity");
#>

<#=accessibility.forreadonlyproperty (entitySet) #> objectset<<#=classname#>> <#=GetClassName (Code. Escape (EntitySet), "Entity") #>
{
get {return <#=code. FieldName (EntitySet) #>?? (<#=code. FieldName (entitySet) #> = createobjectset<<#=classname#>> ("<#=entitySet.Name#>")); }
}
Private objectset<<#=entitysetelementtype#>> <#=code. FieldName (EntitySet) #>;
<#Open the Model1.Context.cs file, you can see the class name inside the batch is also modified as we want to:

6) Testing

C # code generation Tool: Text template first experience class names that use T4 to bulk modify Entity Framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.