Program.cs
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;namespace Migration
{
class Program
{
static void Main(string[] args)
{
string contextFileFullPath = @"D:\\Projects\Context\Context.cs";
string contextContent = File.ReadAllText(contextFileFullPath, Encoding.UTF8);
string savedParentFoldFullPath = @"D:\Mapping"; string regexFindText = @"\s{12}modelBuilder\.Entity\<(?<entityName>\w+)\>\(entity\s*\=\>\S*\s*\{(?<innerCode>[\s\S]*?)\s{13}?\}\)\;"; if (Regex.IsMatch(contextContent, regexFindText))
{
Match matchItem = Regex.Match(contextContent, regexFindText, RegexOptions.Multiline | RegexOptions.IgnoreCase); while (matchItem.Success)
{
string entityName = matchItem.Groups["entityName"].Value;
string innerCode = matchItem.Groups["innerCode"].Value;
WriteToFile(entityName, innerCode, savedParentFoldFullPath);
matchItem = matchItem.NextMatch();
}
Console.WriteLine("The regular expressions are correct, perfect!");
}
else
{
Console.WriteLine("The regular expression is incorrect, please modify!");
}
Console.ReadLine(); } static void WriteToFile(string entityName, string innerCode, string savedParentFoldFullPath)
{
string templateRelativePath = "CodeTemplate.txt";
string templateFullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, templateRelativePath);
string templateContent = File.ReadAllText(templateFullPath, Encoding.UTF8); if (!Directory.Exists(savedParentFoldFullPath))
{
try
{
Directory.CreateDirectory(savedParentFoldFullPath);
}
catch (Exception ex)
{
Console.WriteLine("目录 {0} 创建失败!", ex.Message);
return;
}
} string fileNameWithoutPath = string.Format("{0}Map.cs", entityName);
string savedSingleFileFullPath = Path.Combine(savedParentFoldFullPath, fileNameWithoutPath); string singleFileContent = templateContent
.Replace("{#entityName#}", entityName)
.Replace("{#innerCode#}", innerCode); File.WriteAllText(savedSingleFileFullPath, singleFileContent, Encoding.UTF8);
}
}
}
.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup> <ItemGroup>
<None Update="CodeTemplate.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup></Project>
CodeTemplate.txt
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using XXX.Domain.Core;
using XXX.Ef.Mapping;namespace XXX.Data.Ef.Mapping
{
public class {#entityName#}Map : EntityTypeConfiguration<{#entityName#}>
{
#region Methods /// <summary>
/// Configures the entity
/// </summary>
/// <param name="builder">The builder to be used to configure the entity</param>
public override void Configure(EntityTypeBuilder<{#entityName#}> entity)
{
{#innerCode#}
} #endregion
}
}