private void GenerateContext(CSharpConfig config) { string path = config.DataBase.Path; string file = $"{config.DataBase.ContextName}.cs"; List<string> nameSpaces = new List<string> { "System", "Microsoft.EntityFrameworkCore", "Microsoft.EntityFrameworkCore.Infrastructure", "XCommon.Patterns.Ioc", "XCommon.Application" }; nameSpaces.AddRange(config.DataBaseItems.Select(c => $"{config.DataBase.NameSpace}.{c.Name}")); nameSpaces.AddRange(config.DataBaseItems.Select(c => $"{config.DataBase.NameSpace}.{c.Name}.Map")); StringBuilderIndented builder = new StringBuilderIndented(); builder .GenerateFileMessage() .ClassInit(config.DataBase.ContextName, "DbContext", config.DataBase.NameSpace, ClassVisility.Public, nameSpaces.ToArray()) .AppendLine() .AppendLine("private IApplicationSettings AppSettings => Kernel.Resolve<IApplicationSettings>();") .AppendLine(); foreach (var item in config.DataBaseItems.SelectMany(c => c.Items)) { builder .AppendLine($"public DbSet<{item.Name}> {item.Name} {{ get; set; }}") .AppendLine(); } builder .AppendLine("protected override void OnConfiguring(DbContextOptionsBuilder options)") .AppendLine("{") .IncrementIndent() .AppendLine("if (AppSettings.UnitTest)") .AppendLine("{") .IncrementIndent() .AppendLine($"options") .IncrementIndent() .AppendLine($".UseInMemoryDatabase(\"{config.DataBase.ContextName}\")") .AppendLine(".ConfigureWarnings(config => config.Ignore(InMemoryEventId.TransactionIgnoredWarning));") .DecrementIndent() .AppendLine() .AppendLine("return;") .DecrementIndent() .AppendLine("}") .AppendLine() .AppendLine($"options.UseSqlServer(AppSettings.ConnectionString);") .AppendLine() .DecrementIndent() .AppendLine("}") .AppendLine() .AppendLine("protected override void OnModelCreating(ModelBuilder modelBuilder)") .AppendLine("{"); using (builder.Indent()) { builder .AppendLine(); foreach (var item in config.DataBaseItems.SelectMany(c => c.Items)) { builder.AppendLine($"{item.Name}Map.Map(modelBuilder, AppSettings.UnitTest);"); } } builder .AppendLine("}") .ClassEnd(); WriteFile(path, file, builder); }
private void ProcessMapColumns(StringBuilderIndented builder, Item item) { foreach (var property in item.Properties) { builder .Append($"entity.Property(e => e.{property.Name})"); using (builder.Indent()) { if (!property.Nullable) builder .AppendLine() .Append(".IsRequired()"); if (property.Type == "string" && !string.IsNullOrEmpty(property.Size) && property.Size != "MAX") builder .AppendLine() .Append($".HasMaxLength({property.Size})"); if (property.Key) builder .AppendLine() .Append(".ValueGeneratedNever()"); } builder .Append(";") .AppendLine() .AppendLine(); } }