[原創]EF架構隨心所欲打造屬於你自己的DbModel


前言

   我們都知道EF可以生成Dbmodel,系統生成的Model有時候並不是我們想要的,如何我們要生成自己的Model,那么久需要我們手動的去修改T4模版,T4是對“Text Template Transformation Toolkit”(4個T)的簡稱。如果你對T4不怎么了解可以去看蔣金楠(Artech)文章從數據到代碼——基於T4的代碼生成方式

1.0先看看我們要達到的效果圖吧

 2.0首先我們來修改T4模版吧

   打開T4模版,找到代碼 WriteHeader(codeStringGenerator, fileManager);

我們首先定義變量(圖中黃色代碼為我們自己添加的代碼)

WriteHeader(codeStringGenerator, fileManager);
string summary=string.Empty; 定義變量 foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection))
{
    fileManager.StartNewFile(entity.Name + ".cs");
    BeginNamespace(code);
       if(entity.Documentation !=null && entity.Documentation.Summary!=null) summary=entity.Documentation.Summary; else summary=entity.Name;
#>
<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
using System.ComponentModel.DataAnnotations; 導入你需要的命名空間 /// <summary>
/// <#= summary#>給類加注釋
/// </summary>
[Serializable] <#=codeStringGenerator.EntityClassOpening(entity)#>

看看效果圖如下:

類上面的注釋已經加好了,接下來就是刪除構造函數,刪除以下代碼即可:

    public <#=code.Escape(entity)#>()
    {
<#
        foreach (var edmProperty in propertiesWithDefaultValues)
        {
#>
        this.<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>;
<#
        }

        foreach (var navigationProperty in collectionNavigationProperties)
        {
#>
        this.<#=code.Escape(navigationProperty)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>();
<#
        }

        foreach (var complexProperty in complexProperties)
        {
#>
        this.<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>();
<#
        }
#>
    }

 接下來我們把這些可空類型還原成本來面目,已經去掉virtual關鍵字,修改代碼如下:

public string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace)
    {
        if (edmType == null)
        {
            return null;
        }

        var collectionType = edmType as CollectionType;
        if (collectionType != null)
        {
            return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace));
        }

        var typeName = _code.Escape(edmType.MetadataProperties
                                .Where(p => p.Name == ExternalTypeNameAttributeName)
                                .Select(p => (string)p.Value)
                                .FirstOrDefault())
            ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ?
                _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) :
                _code.Escape(edmType));

        if (edmType is StructuralType)
        {
            return typeName;
        }

        if (edmType is SimpleType)
        {
            var clrType = UnderlyingClrType(edmType);
            if (!IsEnumType(edmType))
            {
                typeName = _code.Escape(clrType);
            }

            typeName = FixNamespaces(typeName);

            return clrType.IsValueType && isNullable == true ? // String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) :原來的代碼
String.Format(CultureInfo.InvariantCulture, "{0}?", typeName) :自己修改的代碼
typeName; }
throw new ArgumentException("edmType"); }
   public string NavigationProperty(NavigationProperty navigationProperty)
    {
        var endType = _typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType());
        return string.Format(
            CultureInfo.InvariantCulture,
            "public {1} {2} {{ {3}get; {4}set; }}",
            AccessibilityAndVirtual(Accessibility.ForProperty(navigationProperty)),
            navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
            _code.Escape(navigationProperty),
            _code.SpaceAfter(Accessibility.ForGetter(navigationProperty)),
            _code.SpaceAfter(Accessibility.ForSetter(navigationProperty)));
    }

接下來來給屬性上添加注釋:(橙色代碼刪除,皇色代碼添加)

/// <summary>
/// <#=            summary#>
/// </summary>
[Serializable]
<#=codeStringGenerator.EntityClassOpening(entity)#>
{
<#
    var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity);
    var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity);
    var complexProperties = typeMapper.GetComplexProperties(entity);

    if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any()) { #>


<# }刪除掉代碼 var simpleProperties = typeMapper.GetSimpleProperties(entity);
    if (simpleProperties.Any())
    {
        foreach (var edmProperty in simpleProperties)
        {

                if (edmProperty.Documentation != null && edmProperty.Documentation.Summary != null) { if(!entity.KeyMembers.Contains(edmProperty.Name)) summary=edmProperty.Documentation.Summary.ToLower().Replace("id","名稱"); else summary=edmProperty.Documentation.Summary; } else { summary=""; }


#>

<#                //if(edmProperty.Name.ToLower() == "id") // continue;var a=edmProperty.Nullable;
                
                var keyName=""; if(entity.KeyMembers.Contains(edmProperty.Name)) keyName="[Key]"; var required=""; if(!edmProperty.Nullable) required="[Required(ErrorMessage = \"請輸入{0}\")]"; string facetName = "MaxLength"; var lengthDes=""; var stringLengthDes=""; int maxLength = 0; if (code.Escape(edmProperty.TypeUsage).ToLower().Contains("string") && Int32.TryParse(edmProperty.TypeUsage.Facets[facetName].Value.ToString(), out maxLength)){ lengthDes="[MaxLength("+maxLength+")]"; stringLengthDes="[StringLength("+maxLength+")]"; } var dataType=""; if (code.Escape(edmProperty.TypeUsage).ToLower().Contains("datetime")) dataType="[DataType(DataType.DateTime)]"; else if (edmProperty.Name.ToLower().Contains("password")) dataType="[DataType(DataType.Password)]"; #>
    /// <summary>
    /// <#=                    summary#>
    /// </summary>
<#                if(!string.IsNullOrWhiteSpace(required)){ #>
    <#=                        required #>
<#                    } if(!string.IsNullOrWhiteSpace(summary)){ #>
    <#=                        "[Display(Name = \""+summary+"\")]" #>
<#                    } if(!string.IsNullOrWhiteSpace(lengthDes)){ #>
    <#=                        lengthDes #>
<#                    } if(!string.IsNullOrWhiteSpace(stringLengthDes)){ #>
    <#=                        stringLengthDes #>
<#                    } if(!string.IsNullOrWhiteSpace(dataType)){ #>
    <#=                        dataType #>
<#                    } if(!string.IsNullOrWhiteSpace(keyName)){ #>
    <#=                        keyName #>
<#                } #>
    <#=codeStringGenerator.Property(edmProperty)#>

 

效果基本已經差不多,可是這里為什么沒有注釋,園子里已經有其他文章來處理這個問題:

1.0EF架構~將數據庫注釋添加導入到模型實體類中 2.0entity framework框架生成摘要文檔為空(沒有元數據文檔可用)的bug解決方案

 

按照步驟做了,可是問題還是沒有解決,怎么辦,其實根本原因是:

主要原因是這里的摘要沒有數據。不斷的嘗試啊,entity framework框架生成摘要文檔為空(沒有元數據文檔可用)的bug解決方案 試了幾次還是沒有從根本上解決問題,怎么辦了...

3.0解決bug

 沒辦法我們查看EFTSQLDocumentation.Generator的源碼終於找到問題所在

        public String ConnectionString { get; set; }
        public String InputFileName { get; set; }
        public String OutputFileName { get; set; }

        private SqlConnection _connection;


        public Program(String connectionString, String inputFileName, String outputFileName)
        {
            this.ConnectionString = connectionString;
            this.InputFileName = inputFileName;
            this.OutputFileName = outputFileName;

            this._connection = new SqlConnection(connectionString);
            this._connection.Open();
        }
        public void Dispose()
        {
            this._connection.Dispose();
        }

        private void CreateDocumentation()
        {

            XDocument doc = XDocument.Load(this.InputFileName);
            IEnumerable<XElement> entityTypeElements = doc.Descendants("{http://schemas.microsoft.com/ado/2008/09/edm}EntityType");

            int i = 0;
            foreach (XElement entityTypeElement in entityTypeElements)
            {
                String tableName = entityTypeElement.Attribute("Name").Value;
                IEnumerable<XElement> propertyElements = entityTypeElement.Descendants("{http://schemas.microsoft.com/ado/2008/09/edm}Property");

                Console.Clear();
                Console.WriteLine("Analyzing table {0} of {1}", i++, entityTypeElements.Count());
                Console.WriteLine(" => TableName : {0}" +
                                  "\n => property count : {1}", tableName, propertyElements.Count());

                this.AddNodeDocumentation(entityTypeElement, GetTableDocumentation(tableName));

                foreach (XElement propertyElement in propertyElements)
                {
                    String columnName = propertyElement.Attribute("Name").Value;
                    this.AddNodeDocumentation(propertyElement, GetColumnDocumentation(tableName, columnName));
                }
            }

            Console.WriteLine("Writing result to {0}", this.OutputFileName);
            if (File.Exists(this.OutputFileName))
                File.Delete(this.OutputFileName);
            doc.Save(this.OutputFileName);
        }
        private void AddNodeDocumentation(XElement element, String documentation)
        {
            if (String.IsNullOrEmpty(documentation))
                return;
            element.Descendants("{http://schemas.microsoft.com/ado/2008/09/edm}Documentation").Remove();

            element.AddFirst(new XElement("{http://schemas.microsoft.com/ado/2008/09/edm}Documentation", new XElement("{http://schemas.microsoft.com/ado/2008/09/edm}Summary", documentation)));
        }
        private String GetTableDocumentation(String tableName)
        {
            using (SqlCommand command = new SqlCommand(@" SELECT [value] 
                                                          FROM fn_listextendedproperty (
                                                                'MS_Description', 
                                                                'schema', 'dbo', 
                                                                'table',  @TableName, 
                                                                null, null)", this._connection))
            {

                command.Parameters.AddWithValue("TableName", tableName);

                return command.ExecuteScalar() as String;
            }
        }
        private String GetColumnDocumentation(String tableName, String columnName)
        {
            using (SqlCommand command = new SqlCommand(@"SELECT [value] 
                                                         FROM fn_listextendedproperty (
                                                                'MS_Description', 
                                                                'schema', 'dbo', 
                                                                'table', @TableName, 
                                                                'column', @columnName)", this._connection))
            {

                command.Parameters.AddWithValue("TableName", tableName);
                command.Parameters.AddWithValue("ColumnName", columnName);

                return command.ExecuteScalar() as String;
            }
        }

我們的edmx中的代碼如下:

      <Schema Namespace="yaochufaNewTestModel.Store" Provider="System.Data.SqlClient" ProviderManifestToken="2008" Alias="Self" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns:customannotation="http://schemas.microsoft.com/ado/2013/11/edm/customannotation" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl">
        <EntityType Name="Activities">
          <Key>
            <PropertyRef Name="ActivityId" />
          </Key>
          <Property Name="ActivityId" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
          <Property Name="ActivityType" Type="int" Nullable="false" />
          <Property Name="ProvinceId" Type="int" />
          <Property Name="CityId" Type="int" />
          <Property Name="Description" Type="nvarchar" MaxLength="50" />
          <Property Name="IsActive" Type="bit" Nullable="false" />
          <Property Name="EndDate" Type="datetime" />
          <Property Name="StartDate" Type="datetime" />
          <Property Name="DrawDate" Type="datetime" />
          <Property Name="DrawInfo" Type="nvarchar" MaxLength="1000" />
          <Property Name="LimitTime" Type="int" />
          <Property Name="ShowStartDate" Type="datetime" />
          <Property Name="ShowEndDate" Type="datetime" />
          <Property Name="PrizeCount" Type="int" />
          <Property Name="ModifiedById" Type="int" />
          <Property Name="ModifiedByName" Type="nvarchar" MaxLength="50" />
          <Property Name="ModifiedDate" Type="datetime" />
          <Property Name="CreatedById" Type="int" Nullable="false" />
          <Property Name="CreatedByName" Type="nvarchar" MaxLength="50" Nullable="false" />
          <Property Name="CreatedDate" Type="datetime" Nullable="false" />
        </EntityType>

需要修改的就是EFTSQLDocumentation.Generator源碼中的xml命名空間我們要替換成 http://schemas.microsoft.com/ado/2009/11/edm最終在cmd中運行如下代碼:

EFTSQLDocumentation.Generator.exe -c "data source=.;initial catalog=yaochufaNewTest;user id=sa;password=123;" -i " D:\Feng.Test\Feng.Test\Model1.edmx"

得到效果圖如下:


免責聲明!

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



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