We just Scaffolded our database, and created Models from Database tables in Entity Framework.
Additionally, we are creating files with Ids which Map to the Primary K
I agree with @Ivan, I wouldn't recommend you this way, but you answered that you need to, so here we go.
You're using EFCore right ? Luckily, EFCore is open-source, so we can dig into the source code and build custom EFCore versions.
A few months ago I had also a specific need with EF Context scaffolding, we also have over 200 tables and needed to put mappings for each table in a separate class, because EF Core, defaults to put all the mapping stuff in the DbContext
file and this generated a 10k+ lines of code long DbContext
class for us
With T4 Research, answer below. People are free to 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);
}
#>
Update:
For some reason, code is also making a copy of the Code Generation T4 File. Trying to fix it now, someone can write new answer, and I will accept it, Thanks.