NET核心:为所有表创建通用存储库接口ID映射自动代码生成 [英] Net Core: Create Generic Repository Interface Id Mapping for All Tables Auto Code Generation
本文介绍了NET核心:为所有表创建通用存储库接口ID映射自动代码生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们刚刚搭建了数据库的脚手架,并从实体框架中的数据库表创建了模型。
此外,我们正在创建具有映射到主键的ID的文件。 这样做的目的是映射到使用ID的通用存储库接口。 如何浏览我所有的200多个型号,并创建一个类似于下面文件2的文件。我在以前的工作场所见过这种情况。我在努力研究。 是否有一个可自动遍历所有模型的Visual Studio或实体框架功能?目前我正在检查每个模型,并手动创建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));
}
或许此资源有帮助? 现在正在尝试让它在我所有的模型文件中循环 How to create multiple output files from a single T4 template using Tangible Editor?
<#@ 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);
}
#>
推荐答案
我同意@ivan的观点,我不建议您这样做,但您回答说您需要这样做,所以我们开始吧。
您正在使用EFCore,对吗?幸运的是,EFCore是开源的,所以我们可以深入研究源代码并构建定制的EFCore版本。
几个月前,我还特别需要EF上下文脚手架,我们还有200多个表,需要将每个表的映射放在一个单独的类中,因为EF核心默认将所有映射内容放在DbContext
文件中,这为我们生成了一个10k多行代码长的DbContext
类。
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("");
如果您确实需要/想要分部类,您只需编写一些代码来在WriteCode
方法中生成另一个文件,该方法每个表调用一次,并且包含此操作所需的所有信息(类型名称等)
Here是用您的定制实现构建项目的代码。搭建完项目的脚手架后,您只需返回到正式的EFCore版本。
这篇关于NET核心:为所有表创建通用存储库接口ID映射自动代码生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文