private void ProcessMapColumns(StringBuilderIndented builder, DataBaseTable item) { foreach (var property in item.Columns) { builder .Append($"entity.Property(e => e.{property.Name})"); using (builder.Indent()) { if (!property.Nullable) { builder .AppendLine() .Append(".IsRequired()"); } if (property.Type == "string" && property.Size.IsNotEmpty() && property.Size != "MAX") { builder .AppendLine() .Append($".HasMaxLength({property.Size})"); } if (property.PK) { builder .AppendLine() .Append(".ValueGeneratedNever()"); } } builder .Append(";") .AppendLine() .AppendLine(); } }
public void WriteContext() { CleanFolder(); var path = Config.CSharp.EntityFramework.Path; var file = $"{Config.CSharp.EntityFramework.ContextName}.cs"; var nameSpaces = new List <string> { "System", "Microsoft.EntityFrameworkCore", "Microsoft.EntityFrameworkCore.Diagnostics", "XCommon.Patterns.Ioc", "XCommon.Application" }; nameSpaces.AddRange(Config.DataBaseItems.Select(c => $"{Config.CSharp.EntityFramework.NameSpace}.{c.Name}")); nameSpaces.AddRange(Config.DataBaseItems.Select(c => $"{Config.CSharp.EntityFramework.NameSpace}.{c.Name}.Map")); var builder = new StringBuilderIndented(); builder .GenerateFileMessage() .ClassInit(Config.CSharp.EntityFramework.ContextName, "DbContext", Config.CSharp.EntityFramework.NameSpace, ClassVisility.Public, nameSpaces.ToArray()) .AppendLine() .AppendLine("private IApplicationSettings AppSettings => Kernel.Resolve<IApplicationSettings>();") .AppendLine(); foreach (var item in Config.DataBaseItems.SelectMany(c => c.Tables)) { 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.CSharp.EntityFramework.ContextName}\")") .AppendLine(".ConfigureWarnings(config => config.Ignore(InMemoryEventId.TransactionIgnoredWarning));") .DecrementIndent() .AppendLine() .AppendLine("return;") .DecrementIndent() .AppendLine("}") .AppendLine() .AppendLine($"options.UseSqlServer(AppSettings.DataBaseConnectionString);") .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.Tables)) { builder.AppendLine($"{item.Name}Map.Map(modelBuilder, AppSettings.UnitTest);"); } } builder .AppendLine("}") .ClassEnd(); Writer.WriteFile(path, file, builder, true); }