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 Key. The purpose of this is to map to our Generic Repository Interface which utilizes Id.
How do I go through all my 200 + models, and create a file similar to file 2 below. I've seen it conducted at previous workplaces. Trying to research. Is there a Visual Studio or Entity framework feature which loops through all models automatically? Currently I am going through each model, and creating the id manually as seen in Generic Id File 2. Willing to implement T4 which implements code generation however other solutions are good.
Scaffolded Files 1:
namespace Datatest
{
public partial class Property
{
public int Property { get; set; }
public int DocumentId { get; set; }
public string Address { get; set; }
}
}
Generic ID File 2:
public partial class Property: IEntity
{
[NotMapped]
public int Id { get => PropertyId; set => PropertyId = value; }
}
Sample Generic Base Repository for all tables:
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));
}
Maybe this resource helps? Trying to make it loop through all my model files now 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);
}
#>