首页 > 解决方案 > 如何更改 T4 模板以将 Serializable 添加到生成的类?

问题描述

正如问题所说,我想将 [Serializable] 添加到从 T4 模板 .tt 文件生成的类中。就我发现的信息而言,我可以使用 System.Runtime.Serialization;和 [Serializable] 作为 .tt 文件中的纯文本作为“文本块”。除了它不会在输出文件中生成这些。

<#
    EndNamespace(code);
}

foreach (var complex in typeMapper.GetItemsToGenerate<ComplexType>(itemCollection))
{
    fileManager.StartNewFile(complex.Name + ".cs");
    BeginNamespace(code);
#>
<#=codeStringGenerator.UsingDirectives(inHeader: false, includeCollections: false)#>
using System.Runtime.Serialization;

[Serializable]
<#=Accessibility.ForType(complex)#> partial class <#=code.Escape(complex)#>
{
<#
    var complexProperties = typeMapper.GetComplexProperties(complex);
    var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(complex);

    if (propertiesWithDefaultValues.Any() || complexProperties.Any())

T4 模板代码

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Projectnamespace.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class Customer
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]

生成的代码

我很想知道这是否有特殊的语法,或者我必须改变什么才能让它工作。

我正在为数据库使用 Visual Studio 2019、.NET Framework 4.7.2、一个 MVC 5 项目和一个 .edmx 文件。

标签: c#-4.0asp.net-mvc-5t4

解决方案


好吧..最终我找到了一种方法来添加“使用 System.Runtime.Serialization;” 通过在 T4 模板中的 UsingDirectives 方法中添加一些行,在每个类中添加“[Serializable]”。通过改变这个:

    public string UsingDirectives(bool inHeader, bool includeCollections = true)
    {
        return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion())
            ? string.Format(
                CultureInfo.InvariantCulture,
                "{0}using System;{1}" +
                "{2}",
                inHeader ? Environment.NewLine : "",
                includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "",
                inHeader ? "" : Environment.NewLine)
            : "";
    }

通过将最后一行编辑为:

    public string UsingDirectives(bool inHeader, bool includeCollections = true)
    {
        return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion())
            ? string.Format(
                CultureInfo.InvariantCulture,
                "{0}using System;{1}" +
                "{2}",
                inHeader ? Environment.NewLine : "",
                includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "",
                inHeader ? "" : Environment.NewLine + "using System.Runtime.Serialization;" + Environment.NewLine + "[Serializable]")
            : "";
    }

推荐阅读