Entity Framework 4 使用T4模板生成實體


數據庫優先模式下,由於數據庫命名和C#命名規范不同,所以感覺很別扭。

首先,創建一個文件,命名隨意,我使用了 EF.CS.Extend.ttinclude 其中方法主要是處理_

<#@ assembly name="System.Core" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#+
public class CodeGenerationHelper
{
   public String FilterUnderline(String code)
    {
        if (String.IsNullOrWhiteSpace(code)) return String.Empty;
        StringBuilder sb = new StringBuilder();

        String[] values = code.Split(new char[] { '_' });
        foreach (string value in values)
        {
            if(String.IsNullOrWhiteSpace(value)) continue;
            sb.Append(value.Substring(0, 1).ToUpper());
            if(value.Length > 1)
                sb.Append(value.Substring(1, value.Length - 1).ToLower());
        }

        return sb.ToString();
    }
}
#>

然后在生成數據庫實體的頭部加入 <#@ include file="EF.CS.Extend.ttinclude"#>

在T4中的各個生成代碼的位置加入過濾方法,這個比較煩,VS2010和VS2012所使用的生成模板不一樣,所以具體需要看情況。

最后看看生成的代碼,哈哈

[Table("Take_Office")]
public partial class TakeOffice
{

	[Column("id")]
	public long Id { get; set; }

	[Column("pers_code")]
	public string PersCode { get; set; }

	[Column("if_public_code")]
	public Nullable<short> IfPublicCode { get; set; }

	[Column("if_public_name")]
	public string IfPublicName { get; set; }

	[Column("public_form_code")]
	public Nullable<short> PublicFormCode { get; set; }

	[Column("public_form_name")]
	public string PublicFormName { get; set; }
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM