To generate T4 template of SERVER EF code for SQL

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

We do in small website, often have to spend a lot of time to write the entity class, data access class, business class. These things are done, to make UI and specific business, is a bit back oil ah, although there are some generation tool can generate, but will take some effort to modify the adapt project, so in this study the T4 template (), and simple and rough as a tool.

According to SQL, EF code generation, can generate:

The entity class: Model, for mapping database tables.

Data access: the only way of EF

Business class: after the production to complete the basic add, delete, query function

The code you write greasy, the word does not say more, have a look have a look first code, thought from the code, the following is part of the code:

The 1 entity classes

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace model
{

    [Table("AccountBook")]
    public class AccountBook : BaseModelGuid
    {
        public int? AccountCode { get; set; }
        public DateTime? CreateTime { get; set; }
        public int? Creater { get; set; }
        public string Remark { get; set; }
        public bool? IsDelete { get; set; }
    }
}

 Generate entity classes about such a look, you will notice that the entity classes are derived from the BaseModelGuid class, in fact here is done with a constraint, time constraint in your database design, database table must have a primary key field named ID, nvarchar (36), is actually used to save GUID in so doing, why, when generating business class to explain. Look at the base of the code:

public class BaseModel<T>
    {
        [Key]
        public T Id { get; set; }
    }

public class BaseModelGuid : BaseModel<string>
    {
        public BaseModelGuid()
        {
            Id = System.Guid.NewGuid().ToString();
        }
    }

 The idea here is that each table corresponds to the primary key of the entity classes are placed in the base class, entity class in the generated code is very simple, have a look the template:

<#@ template language="C#" #>
<#@ assembly name="System.Core.dll" #>
<#@ assembly name="System.ComponentModel.DataAnnotations.dll" #>
<#@ assembly name="The F:\ project \EFPocoCSCreater\EFPocoCSCreater\EFPocoCSCreater.UseModel\bin\Debug\EFPocoCSCreater.UseModel.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.ComponentModel.DataAnnotations" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="EFPocoCSCreater.UseModel" #>

<#@ parameter name="TempModel" type="EFPocoCSCreater.UseModel.CreaterModel" #>

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace model
{
	
	[Table("<#= TempModel==null?"":TempModel.TableName #>")]
	public class <#= TempModel==null?"A":TempModel.TableName #> : BaseModelGuid
	{
		<# if(TempModel!=null && TempModel.Fields!=null){ foreach (var item in TempModel.Fields){ #>
		public <#= item.CsDataType #> <#= item.Name #> { get; set; }
		<# }} #>
	}
}

2 data access class

Have a look first generation code:

public class BaseDataAccess : DbContext
    {
        public BaseDataAccess()
            : base("DataBaseURL")
        {
            SetInitializer();
        }

        /// <summary>
        /// Initialization of EF DbContext
        /// </summary>
        protected virtual void SetInitializer()
        {
            //Database.SetInitializer<DProjectFileInfo>(null);
        }
    }

public class DataAccess : BaseDataAccess
    {
        protected override void SetInitializer()
        {
            Database.SetInitializer<DataAccess>(null);
        }

        public DbSet<AccountBook> AccountBook { get; set; }
        public DbSet<AccountInCome> AccountInCome { get; set; }
        public DbSet<AccountInfo> AccountInfo { get; set; }
        public DbSet<AccountType> AccountType { get; set; }
        public DbSet<AccountUseType> AccountUseType { get; set; }
        public DbSet<TBUser> TBUser { get; set; }
        public DbSet<V_AccountBook> V_AccountBook { get; set; }
        public DbSet<V_AccountInfo> V_AccountInfo { get; set; }

    }

  This piece of nothing to say, here EF I to generate a table mapping very lazy together, ha ha. The template is very simple:

<#@ template language="C#" #>
<#@ assembly name="System.Core.dll" #>
<#@ assembly name="System.Data.Entity.dll" #>
<#@ assembly name="The F:\ project \EFPocoCSCreater\EFPocoCSCreater\EFPocoCSCreater.UseModel\bin\Debug\EFPocoCSCreater.UseModel.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Data.Entity" #>
<#@ import namespace="EFPocoCSCreater.UseModel" #>

<#@ parameter name="TempModel" type="EFPocoCSCreater.UseModel.CreaterDataAccess" #>

using System;
using System.Data.Entity;

namespace dataaccess
{
	public class DataAccess : BaseDataAccess
    {
		protected override void SetInitializer()
        {
            Database.SetInitializer<DataAccess>(null);
        }

		<# if(TempModel!=null && TempModel.TablesName!=null){ foreach (var item in TempModel.TablesName){ #>
		public DbSet<<#= item #>> <#= item #> { get; set; }
		<# }} #>

	}
}

 3 business class

Business class is generated for each table object, but the initial code rarely:

using System;
using System.Collections.Generic;
using System.Linq;

namespace business
{
	public class BAccountBook : BaseBusinessString<AccountBook>
    {
        public BAccountBook()
            : base(new DataAccess())
        {

        }
    }
}

 The initial generation to complete the basic add, delete, query functions on the base, the base class uses generics, constraints of the derived class, it also integrates according to ID delete, search operation in the base class, the following posted part class code:

public class BaseBusinessString<T> : BaseBusiness<T, string> where T : BaseModel<string>
    {
        public BaseBusinessString(DbContext context)
            : base(context)
        {

        }

        /// <summary>
        /// The primary key query
        /// </summary>
        /// <param name="id">The key Id</param>
        /// <returns></returns>
        public T FindById(string id)
        {
            return FindByPredicate(p => p.Id == id);
        }

        /// <summary>
        /// According to the Id delete
        /// </summary>
        /// <param name="id"></param>
        protected virtual void PDeleteById(string id)
        {
            PDeleteByModel(FindById(id));
        }

        /// <summary>
        /// According to the Id delete
        /// </summary>
        /// <param name="id"></param>
        public virtual bool DeleteById(string id)
        {
            PDeleteByModel(FindById(id));
            return Context.SaveChanges() > 0;
        }
    }

 In this way, can generate well able to cope with the small website project entity class, data access, basic business class, the rest of the time just for the specific business and UI.

Finally, to talk about this tool, very rough, very simple, very targeted (basically is aimed at the CsTemp directory within the code generation).

There were only the template T4, read the database, encapsulation of some base class.

In the program directory:

CS Code: The generated code directory

CsTemp: Base on the generated code from code

Dll: Relying on the generated code DLL file

Temp: The T4 template file directory


The next step is to upload the source code, code written in very ugly, carefully watch ah, but also hope that the defect

Code



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Edmund at November 15, 2013 - 6:20 AM