Net Core:为所有表自动代码生成创建通用存储库接口 ID 映射

Net Core: Create Generic Repository Interface Id Mapping for All Tables Auto Code Generation

我们只是搭建了我们的数据库,并从 Entity Framework 中的数据库表创建了模型。

此外,我们正在创建具有映射到主键的 ID 的文件。 这样做的目的是映射到我们使用 Id 的通用存储库接口。

如何浏览我所有的 200 多个模型,并创建一个类似于下面文件 2 的文件。我已经在以前的工作场所看到过它。正在努力研究。 是否有自动循环遍历所有模型的 Visual Studio 或 Entity framework 功能?目前我正在浏览每个模型,并手动创建 ID,如通用 ID 文件 2 中所示。愿意实施实现代码生成的 T4,但其他解决方案也不错。

脚手架文件 1:

namespace Datatest
{
    public partial class Property
    {
        public int Property { get; set; }
        public int DocumentId { get; set; }
        public string Address { get; set; }
    }
}

通用 ID 文件 2:

public partial class Property: IEntity
{
    [NotMapped]
    public int Id { get => PropertyId; set => PropertyId = value; }
}

所有表的示例通用基础存储库:

    public T Get(int id)
    {
        return Table.Find(id);
    }
    public async Task<T> GetAsync(int id)
    {
        return await Table.FindAsync(id);
    }
    public T Single(Expression<Func<T, bool>> predicate)
    {
        return All.Single(predicate);
    }
    public async Task<T> SingleAsync(Expression<Func<T, bool>> predicate)
    {
        return await All.SingleAsync(predicate);
    }
    public T FirstOrDefault(int id)
    {
        return All.FirstOrDefault(CreateEqualityExpressionForId(id));
    }

也许此资源有帮助? 现在试着让它循环遍历我所有的模型文件

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ output extension=".txt" #>
<#
for (Int32 i = 0; i < 10; ++i) {
#>
Content <#= i #>
<#
  // End of file.
  SaveOutput("Content" + i.ToString() + ".cs");
}
#>
<#+
private void SaveOutput(string outputFileName) {
  string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
  string outputFilePath = Path.Combine(templateDirectory, outputFileName);
  File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); 
  this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
}
#>

T4 Research,请在下方回答。人们可以自由 edit/optimize.

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>

<#
    DirectoryInfo d = new DirectoryInfo(Path.GetDirectoryName(this.Host.TemplateFile) + @"\Scaffold");
    FileInfo[] Files = d.GetFiles("*.cs");
    string str = "";

    foreach(FileInfo file in Files )
    {
        var modelName = Path.GetFileNameWithoutExtension(file.Name);
#>
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

namespace Data.Entities
{
    public partial class <#=modelName #> : IEntity, IAuditedEntity
    {
        [NotMapped]
        public int Id { get => <#=modelName #>Id; set => <#=modelName #>Id = value; }
    }
}

<#
  // End of file.
  SaveOutput(file.Name.ToString());
}
#>
<#+
    private void SaveOutput(string outputFileName) {
      string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
      string outputFilePath = Path.Combine(templateDirectory, outputFileName);
      File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); 
      this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
    }
#>

更新:

出于某种原因,代码也在制作代码生成 T4 文件的副本。现在正在尝试修复它,有人可以写新答案,我会接受,谢谢。

我同意@Ivan,我不会推荐你这样,但你回答说你需要,所以我们开始吧。

您使用的是 EFCore 吗?幸运的是,EFCore 是开源的,因此我们可以深入研究源代码并构建自定义 EFCore 版本。

几个月前,我对 EF Context 脚手架也有特殊需求,我们也有 200 多个 table,需要将每个 table 的映射放在单独的 class,因为 EF Core 默认将所有映射内容放在 DbContext 文件中,这为我们生成了 10k+ 行长 DbContext class 的代码。

EntityTypes代处理here。对你来说有趣的是 #109 :

_sb.AppendLine($"public partial class {entityType.Name}");

在这里你可以这样添加你的界面:

_sb.AppendLine($"public partial class {entityType.Name} : IEntity");

然后我们必须实现您的接口,在线 #113 我们有以下代码:

using (_sb.Indent())
{
   GenerateConstructor(entityType);
   GenerateProperties(entityType);
   GenerateNavigationProperties(entityType);
}

就在 GenerateProperties(entityType); 之前,您可以添加以下行来实现接口规范:

_sb.AppendLine("[NotMapped]");
_sb.AppendLine("public int Id { get => PropertyId; set => PropertyId = value; }");
_sb.AppendLine("");

如果你真的 need/want 部分 classes 你可以简单地写一些代码来在 WriteCode 方法中生成另一个文件,每个 table 调用一次并且有为此所需的所有信息(类型名称等)

Here 是使用自定义实现构建项目的代码。在构建项目后,您可以 return 进行官方 EFCore 构建。