From d6cdb7ed1d398ee83428d86b6037f0252ab63b17 Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Fri, 22 Apr 2022 09:05:32 +0800 Subject: [PATCH] Using file-scoped namespace and add license header --- src/DbTool/App.xaml.cs | 170 ++-- src/DbTool/AssemblyInfo.cs | 3 + src/DbTool/ConfigurationConstants.cs | 58 +- src/DbTool/ConfigurationHelper.cs | 100 +-- .../Converters/FullTableNameConverter.cs | 28 +- src/DbTool/CsvDbDoc.cs | 7 +- src/DbTool/ExcelDbDoc.cs | 236 +++--- src/DbTool/Extensions/DbEntityExtensions.cs | 22 +- src/DbTool/Extensions/DictionaryExtensions.cs | 18 +- src/DbTool/Localization/LocalizerExtension.cs | 40 +- src/DbTool/MainWindow.xaml.cs | 792 +++++++++--------- src/DbTool/Services/ModelNameConverter.cs | 42 +- src/DbTool/ViewModels/CheckableTableEntity.cs | 40 +- src/DbTool/ViewModels/SettingsViewModel.cs | 214 ++--- test/DbTool.Test/NameConverterTest.cs | 64 +- 15 files changed, 933 insertions(+), 901 deletions(-) diff --git a/src/DbTool/App.xaml.cs b/src/DbTool/App.xaml.cs index af81191..02447a6 100644 --- a/src/DbTool/App.xaml.cs +++ b/src/DbTool/App.xaml.cs @@ -1,10 +1,6 @@ -using System; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Runtime.Loader; -using System.Threading; -using System.Windows; +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + using DbTool.Core; using DbTool.DbProvider.MySql; using DbTool.DbProvider.PostgreSql; @@ -12,107 +8,113 @@ using DbTool.ViewModels; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using System; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.Loader; +using System.Threading; +using System.Windows; using WeihanLi.Common; using WeihanLi.Common.Helpers; using WeihanLi.Extensions.Localization.Json; using WeihanLi.Npoi; -namespace DbTool +namespace DbTool; + +/// +/// Interaction logic for App.xaml +/// +public partial class App { - /// - /// Interaction logic for App.xaml - /// - public partial class App + protected override void OnStartup(StartupEventArgs e) { - protected override void OnStartup(StartupEventArgs e) - { - Init(); - base.OnStartup(e); - } + Init(); + base.OnStartup(e); + } - private static void ConfigureServices(IServiceCollection services) - { - services.TryAddTransient(); - services.AddJsonLocalization(options => options.ResourcesPathType = ResourcesPathType.CultureBased); - - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - - services - .AddDbProvider() - .AddDbProvider() - .AddDbProvider() - ; - - services.AddDbDocExporter() - .AddDbDocExporter() - ; - services.AddDbDocImporter() - .AddDbDocImporter() - ; - } + private static void ConfigureServices(IServiceCollection services) + { + services.TryAddTransient(); + services.AddJsonLocalization(options => options.ResourcesPathType = ResourcesPathType.CultureBased); + + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + + services + .AddDbProvider() + .AddDbProvider() + .AddDbProvider() + ; + + services.AddDbDocExporter() + .AddDbDocExporter() + ; + services.AddDbDocImporter() + .AddDbDocImporter() + ; + } - private static void Init() - { - #region Init Settings + private static void Init() + { + #region Init Settings - FluentSettings.LoadMappingProfiles(typeof(ColumnEntityMappingProfile).Assembly); + FluentSettings.LoadMappingProfiles(typeof(ColumnEntityMappingProfile).Assembly); - var settings = new SettingsViewModel(); - settings.ConnectionString = settings.DefaultConnectionString; - // set current culture - Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(settings.DefaultCulture); - Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(settings.DefaultCulture); + var settings = new SettingsViewModel(); + settings.ConnectionString = settings.DefaultConnectionString; + // set current culture + Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(settings.DefaultCulture); + Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(settings.DefaultCulture); - #endregion Init Settings + #endregion Init Settings - #region Init Services and plugins + #region Init Services and plugins - IServiceCollection services = new ServiceCollection(); - services.AddSingleton(settings); - ConfigureServices(services); + IServiceCollection services = new ServiceCollection(); + services.AddSingleton(settings); + ConfigureServices(services); + // load plugins + var interfaces = typeof(IDbProvider).Assembly + .GetExportedTypes() + .Where(x => x.IsInterface) + .ToArray(); + var pluginDir = ApplicationHelper.MapPath("plugins"); + if (Directory.Exists(pluginDir)) + { // load plugins - var interfaces = typeof(IDbProvider).Assembly - .GetExportedTypes() - .Where(x => x.IsInterface) + var plugins = Directory.GetFiles(pluginDir) + .Where(_ => _.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) .ToArray(); - var pluginDir = ApplicationHelper.MapPath("plugins"); - if (Directory.Exists(pluginDir)) + if (plugins.Length > 0) { - // load plugins - var plugins = Directory.GetFiles(pluginDir) - .Where(_ => _.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) + var assemblies = plugins.Select(AssemblyLoadContext.Default.LoadFromAssemblyPath).ToArray(); + var exportedTypes = assemblies + .Select(x => x.GetExportedTypes()) + .SelectMany(t => t) + .Where(t => !t.IsInterface && !t.IsAbstract) + .ToArray(); + var pluginTypes = exportedTypes + .Where(t => interfaces.Any(i => i.IsAssignableFrom(t))) .ToArray(); - if (plugins.Length > 0) + foreach (var type in pluginTypes) { - var assemblies = plugins.Select(AssemblyLoadContext.Default.LoadFromAssemblyPath).ToArray(); - var exportedTypes = assemblies - .Select(x => x.GetExportedTypes()) - .SelectMany(t => t) - .Where(t => !t.IsInterface && !t.IsAbstract) - .ToArray(); - var pluginTypes = exportedTypes - .Where(t => interfaces.Any(i => i.IsAssignableFrom(t))) - .ToArray(); - foreach (var type in pluginTypes) - { - services.RegisterTypeAsImplementedInterfaces(type); - } - - // load service modules - services.RegisterAssemblyModules(assemblies); + services.RegisterTypeAsImplementedInterfaces(type); } + + // load service modules + services.RegisterAssemblyModules(assemblies); } + } - DependencyResolver.SetDependencyResolver(services); + DependencyResolver.SetDependencyResolver(services); - #endregion Init Services and plugins + #endregion Init Services and plugins - DependencyResolver.ResolveRequiredService().Show(); - } + DependencyResolver.ResolveRequiredService().Show(); } } diff --git a/src/DbTool/AssemblyInfo.cs b/src/DbTool/AssemblyInfo.cs index 8b5504e..5140dd2 100644 --- a/src/DbTool/AssemblyInfo.cs +++ b/src/DbTool/AssemblyInfo.cs @@ -1,3 +1,6 @@ +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + using System.Windows; [assembly: ThemeInfo( diff --git a/src/DbTool/ConfigurationConstants.cs b/src/DbTool/ConfigurationConstants.cs index 0d83c0d..5950fb2 100644 --- a/src/DbTool/ConfigurationConstants.cs +++ b/src/DbTool/ConfigurationConstants.cs @@ -1,35 +1,37 @@ -namespace DbTool +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + +namespace DbTool; + +internal static class ConfigurationConstants { - internal static class ConfigurationConstants - { - /// - /// Excel 模板下载地址 - /// - public const string ExcelTemplateDownloadLink = "ExcelTemplateDownloadLink"; + /// + /// Excel 模板下载地址 + /// + public const string ExcelTemplateDownloadLink = "ExcelTemplateDownloadLink"; - /// - /// 默认连接字符串 - /// - public const string DefaultConnectionString = "DefaultConnString"; + /// + /// 默认连接字符串 + /// + public const string DefaultConnectionString = "DefaultConnString"; - /// - /// 数据库类型 - /// - public const string DbType = "DbType"; + /// + /// 数据库类型 + /// + public const string DbType = "DbType"; - /// - /// 生成数据库描述类型 - /// - public const string GenerateDbDescription = "GenerateDbDescription"; + /// + /// 生成数据库描述类型 + /// + public const string GenerateDbDescription = "GenerateDbDescription"; - /// - /// 生成私有字段 - /// - public const string GeneratePrivateField = "GeneratePrivateField"; + /// + /// 生成私有字段 + /// + public const string GeneratePrivateField = "GeneratePrivateField"; - /// - /// 生成 [Description]/[Table] 等注解 - /// - public const string GenerateDataAnnotation = "GenerateDataAnnotation"; - } + /// + /// 生成 [Description]/[Table] 等注解 + /// + public const string GenerateDataAnnotation = "GenerateDataAnnotation"; } diff --git a/src/DbTool/ConfigurationHelper.cs b/src/DbTool/ConfigurationHelper.cs index b68ef04..a8d0c98 100644 --- a/src/DbTool/ConfigurationHelper.cs +++ b/src/DbTool/ConfigurationHelper.cs @@ -1,58 +1,60 @@ -using System.Collections.Specialized; +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Specialized; using System.Configuration; using WeihanLi.Extensions; -namespace DbTool +namespace DbTool; + +/// +/// Helper for ConfigurationManager +/// https://github.com/WeihanLi/WeihanLi.Common/blob/dev/src/WeihanLi.Common/Helpers/ConfigurationHelper.cs +/// +public static class ConfigurationHelper { + private static NameValueCollection _appSettings; + + static ConfigurationHelper() + { + _appSettings = ConfigurationManager.AppSettings; + } + + /// + /// 获取配置文件中AppSetting节点的值 + /// + /// 设置的键值 + /// 键值对应的值 + public static string AppSetting(string key) => _appSettings[key] ?? string.Empty; + + /// + /// 获取配置文件中AppSetting节点的值 + /// + /// 设置的键值 + /// 键值对应的值 + public static T AppSetting(string key) => AppSetting(key).StringToType(); + + /// + /// 更新 AppSetting 配置 + /// + /// value type + /// app setting key + /// app setting value + public static void UpdateAppSetting(string key, T value) => UpdateAppSetting(key, value.ToJsonOrString()); + /// - /// Helper for ConfigurationManager - /// https://github.com/WeihanLi/WeihanLi.Common/blob/dev/src/WeihanLi.Common/Helpers/ConfigurationHelper.cs + /// 更新 AppSetting 配置 /// - public static class ConfigurationHelper + /// app setting key + /// app setting value + public static void UpdateAppSetting(string key, string value) { - private static NameValueCollection _appSettings; - - static ConfigurationHelper() - { - _appSettings = ConfigurationManager.AppSettings; - } - - /// - /// 获取配置文件中AppSetting节点的值 - /// - /// 设置的键值 - /// 键值对应的值 - public static string AppSetting(string key) => _appSettings[key] ?? string.Empty; - - /// - /// 获取配置文件中AppSetting节点的值 - /// - /// 设置的键值 - /// 键值对应的值 - public static T AppSetting(string key) => AppSetting(key).StringToType(); - - /// - /// 更新 AppSetting 配置 - /// - /// value type - /// app setting key - /// app setting value - public static void UpdateAppSetting(string key, T value) => UpdateAppSetting(key, value.ToJsonOrString()); - - /// - /// 更新 AppSetting 配置 - /// - /// app setting key - /// app setting value - public static void UpdateAppSetting(string key, string value) - { - var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); - config.AppSettings.Settings.Remove(key); - config.AppSettings.Settings.Add(key, value); - config.Save(ConfigurationSaveMode.Minimal); - // Force a reload of a changed section. - ConfigurationManager.RefreshSection("appSettings"); - _appSettings = ConfigurationManager.AppSettings; - } + var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); + config.AppSettings.Settings.Remove(key); + config.AppSettings.Settings.Add(key, value); + config.Save(ConfigurationSaveMode.Minimal); + // Force a reload of a changed section. + ConfigurationManager.RefreshSection("appSettings"); + _appSettings = ConfigurationManager.AppSettings; } } diff --git a/src/DbTool/Converters/FullTableNameConverter.cs b/src/DbTool/Converters/FullTableNameConverter.cs index e35c854..b241817 100644 --- a/src/DbTool/Converters/FullTableNameConverter.cs +++ b/src/DbTool/Converters/FullTableNameConverter.cs @@ -1,21 +1,23 @@ -using System; +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + +using DbTool.Core.Entity; +using System; using System.Globalization; using System.Windows.Data; -using DbTool.Core.Entity; -namespace DbTool.Converters +namespace DbTool.Converters; + +[ValueConversion(typeof(TableEntity), typeof(string))] +public class FullTableNameConverter : IValueConverter { - [ValueConversion(typeof(TableEntity), typeof(string))] - public class FullTableNameConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value is TableEntity tableEntity ? tableEntity.GetFullTableName() : string.Empty; - } + return value is TableEntity tableEntity ? tableEntity.GetFullTableName() : string.Empty; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/src/DbTool/CsvDbDoc.cs b/src/DbTool/CsvDbDoc.cs index a87ec3e..4b44bd2 100644 --- a/src/DbTool/CsvDbDoc.cs +++ b/src/DbTool/CsvDbDoc.cs @@ -1,7 +1,10 @@ -using System.Collections.Generic; -using System.Linq; +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + using DbTool.Core; using DbTool.Core.Entity; +using System.Collections.Generic; +using System.Linq; using WeihanLi.Common.Helpers; using WeihanLi.Extensions; using WeihanLi.Npoi; diff --git a/src/DbTool/ExcelDbDoc.cs b/src/DbTool/ExcelDbDoc.cs index ebe9943..0a60889 100644 --- a/src/DbTool/ExcelDbDoc.cs +++ b/src/DbTool/ExcelDbDoc.cs @@ -1,146 +1,148 @@ -using System.Collections.Generic; -using System.Linq; +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + using DbTool.Core; using DbTool.Core.Entity; using NPOI.SS.UserModel; using NPOI.SS.Util; +using System.Collections.Generic; +using System.Linq; using WeihanLi.Npoi; using WeihanLi.Npoi.Configurations; -namespace DbTool +namespace DbTool; + +public sealed class ExcelDbDocImporter : IDbDocImporter { - public sealed class ExcelDbDocImporter : IDbDocImporter - { - public string ImportType => "Excel"; + public string ImportType => "Excel"; - public Dictionary SupportedFileExtensions => new() - { - { ".xls", "Excel file(*.xls)" }, - { ".xlsx", "Excel file(*.xlsx)" } - }; + public Dictionary SupportedFileExtensions => new() + { + { ".xls", "Excel file(*.xls)" }, + { ".xlsx", "Excel file(*.xlsx)" } + }; - public TableEntity[] Import(string filePath, IDbProvider dbProvider) + public TableEntity[] Import(string filePath, IDbProvider dbProvider) + { + var workbook = ExcelHelper.LoadExcel(filePath); + var tables = new TableEntity[workbook.NumberOfSheets]; + for (var i = 0; i < workbook.NumberOfSheets; i++) { - var workbook = ExcelHelper.LoadExcel(filePath); - var tables = new TableEntity[workbook.NumberOfSheets]; - for (var i = 0; i < workbook.NumberOfSheets; i++) + var sheet = workbook.GetSheetAt(i); + tables[i] = new TableEntity { - var sheet = workbook.GetSheetAt(i); - tables[i] = new TableEntity - { - TableName = sheet.SheetName, - TableDescription = sheet.GetRow(0).GetCell(0).StringCellValue - }; - tables[i].Columns.AddRange(sheet.ToEntityList() - .Where(x => !string.IsNullOrEmpty(x?.ColumnName)) - ); - } - - return tables; + TableName = sheet.SheetName, + TableDescription = sheet.GetRow(0).GetCell(0).StringCellValue + }; + tables[i].Columns.AddRange(sheet.ToEntityList() + .Where(x => !string.IsNullOrEmpty(x?.ColumnName)) + ); } + + return tables; } +} - public sealed class ExcelDbDocExporter : IDbDocExporter - { - public string ExportType => "Excel"; +public sealed class ExcelDbDocExporter : IDbDocExporter +{ + public string ExportType => "Excel"; - public string FileExtension => ".xlsx"; + public string FileExtension => ".xlsx"; - public byte[] Export(TableEntity[] tableInfo, IDbProvider dbProvider) + public byte[] Export(TableEntity[] tableInfo, IDbProvider dbProvider) + { + var workbook = + ExcelHelper.PrepareWorkbook(FileExtension.EndsWith(".xls") ? ExcelFormat.Xls : ExcelFormat.Xlsx); + foreach (var tableEntity in tableInfo) { - var workbook = - ExcelHelper.PrepareWorkbook(FileExtension.EndsWith(".xls") ? ExcelFormat.Xls : ExcelFormat.Xlsx); - foreach (var tableEntity in tableInfo) - { - var sheet = workbook.CreateSheet(tableEntity.TableName); - - var titleRow = sheet.CreateRow(0); - var titleCell = titleRow.CreateCell(0); - titleCell.SetCellValue(tableEntity.NotEmptyDescription); + var sheet = workbook.CreateSheet(tableEntity.TableName); - sheet.ImportData(tableEntity.Columns); - } + var titleRow = sheet.CreateRow(0); + var titleCell = titleRow.CreateCell(0); + titleCell.SetCellValue(tableEntity.NotEmptyDescription); - return workbook.ToExcelBytes(); + sheet.ImportData(tableEntity.Columns); } + + return workbook.ToExcelBytes(); } +} - public sealed class ColumnEntityMappingProfile : IMappingProfile +public sealed class ColumnEntityMappingProfile : IMappingProfile +{ + public void Configure(IExcelConfiguration settings) { - public void Configure(IExcelConfiguration settings) - { - settings.HasExcelSetting(x => { x.Author = "DbTool"; }) - .HasSheetSetting(x => + settings.HasExcelSetting(x => { x.Author = "DbTool"; }) + .HasSheetSetting(x => + { + x.StartRowIndex = 2; + x.AutoColumnWidthEnabled = true; + x.RowAction = row => { - x.StartRowIndex = 2; - x.AutoColumnWidthEnabled = true; - x.RowAction = row => + // apply header row style + if (row.RowNum == 1) { - // apply header row style - if (row.RowNum == 1) - { - var headerStyle = row.Sheet.Workbook.CreateCellStyle(); - headerStyle.Alignment = HorizontalAlignment.Center; - var headerFont = row.Sheet.Workbook.CreateFont(); - headerFont.FontHeight = 180; - headerFont.IsBold = true; - headerFont.FontName = "微软雅黑"; - headerStyle.SetFont(headerFont); - row.Cells.ForEach(c => c.CellStyle = headerStyle); - } - }; - x.SheetAction = sheet => - { - // set merged region - sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 6)); - // apply title style - var titleStyle = sheet.Workbook.CreateCellStyle(); - titleStyle.Alignment = HorizontalAlignment.Left; - var font = sheet.Workbook.CreateFont(); - font.FontHeight = 200; - font.FontName = "微软雅黑"; - font.IsBold = true; - titleStyle.SetFont(font); - titleStyle.FillBackgroundColor = IndexedColors.Black.Index; - titleStyle.FillForegroundColor = IndexedColors.SeaGreen.Index; - titleStyle.FillPattern = FillPattern.SolidForeground; - sheet.GetRow(0).GetCell(0).CellStyle = titleStyle; - }; - }); - settings.Property(x => x.ColumnName) - .HasColumnIndex(0) - .HasColumnTitle("列名称"); - settings.Property(x => x.ColumnDescription) - .HasColumnIndex(1) - .HasColumnTitle("列描述"); - settings.Property(x => x.IsPrimaryKey) - .HasColumnIndex(2) - .HasColumnTitle("是否主键") - .HasColumnOutputFormatter(x => x ? "Y" : "N") - .HasColumnInputFormatter(x => "Y".Equals(x)); - settings.Property(x => x.IsNullable) - .HasColumnIndex(3) - .HasColumnTitle("是否可以为空") - .HasColumnOutputFormatter(x => x ? "Y" : "N") - .HasColumnInputFormatter(x => "Y".Equals(x)); - settings.Property(x => x.DataType) - .HasColumnIndex(4) - .HasColumnTitle("数据类型") - .HasColumnOutputFormatter(x => x?.ToUpper()); - settings.Property(x => x.Size) - .HasColumnIndex(5) - .HasColumnTitle("数据长度") - .HasColumnOutputFormatter(x => x > 0 && x < int.MaxValue ? x.ToString() : string.Empty); - settings.Property(x => x.DefaultValue) - .HasColumnIndex(6) - .HasColumnTitle("默认值") - .HasOutputFormatter((x, _) => + var headerStyle = row.Sheet.Workbook.CreateCellStyle(); + headerStyle.Alignment = HorizontalAlignment.Center; + var headerFont = row.Sheet.Workbook.CreateFont(); + headerFont.FontHeight = 180; + headerFont.IsBold = true; + headerFont.FontName = "微软雅黑"; + headerStyle.SetFont(headerFont); + row.Cells.ForEach(c => c.CellStyle = headerStyle); + } + }; + x.SheetAction = sheet => { - if (x?.DefaultValue != null) return x.DefaultValue.ToString(); - if (x?.IsPrimaryKey == true && x.DataType.ToUpper().Contains("INT")) return "IDENTITY(1,1)"; - return null; - }); - settings.Property(x => x.NotEmptyDescription).Ignored(); - } + // set merged region + sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 6)); + // apply title style + var titleStyle = sheet.Workbook.CreateCellStyle(); + titleStyle.Alignment = HorizontalAlignment.Left; + var font = sheet.Workbook.CreateFont(); + font.FontHeight = 200; + font.FontName = "微软雅黑"; + font.IsBold = true; + titleStyle.SetFont(font); + titleStyle.FillBackgroundColor = IndexedColors.Black.Index; + titleStyle.FillForegroundColor = IndexedColors.SeaGreen.Index; + titleStyle.FillPattern = FillPattern.SolidForeground; + sheet.GetRow(0).GetCell(0).CellStyle = titleStyle; + }; + }); + settings.Property(x => x.ColumnName) + .HasColumnIndex(0) + .HasColumnTitle("列名称"); + settings.Property(x => x.ColumnDescription) + .HasColumnIndex(1) + .HasColumnTitle("列描述"); + settings.Property(x => x.IsPrimaryKey) + .HasColumnIndex(2) + .HasColumnTitle("是否主键") + .HasColumnOutputFormatter(x => x ? "Y" : "N") + .HasColumnInputFormatter(x => "Y".Equals(x)); + settings.Property(x => x.IsNullable) + .HasColumnIndex(3) + .HasColumnTitle("是否可以为空") + .HasColumnOutputFormatter(x => x ? "Y" : "N") + .HasColumnInputFormatter(x => "Y".Equals(x)); + settings.Property(x => x.DataType) + .HasColumnIndex(4) + .HasColumnTitle("数据类型") + .HasColumnOutputFormatter(x => x?.ToUpper()); + settings.Property(x => x.Size) + .HasColumnIndex(5) + .HasColumnTitle("数据长度") + .HasColumnOutputFormatter(x => x > 0 && x < int.MaxValue ? x.ToString() : string.Empty); + settings.Property(x => x.DefaultValue) + .HasColumnIndex(6) + .HasColumnTitle("默认值") + .HasOutputFormatter((x, _) => + { + if (x?.DefaultValue != null) return x.DefaultValue.ToString(); + if (x?.IsPrimaryKey == true && x.DataType.ToUpper().Contains("INT")) return "IDENTITY(1,1)"; + return null; + }); + settings.Property(x => x.NotEmptyDescription).Ignored(); } } diff --git a/src/DbTool/Extensions/DbEntityExtensions.cs b/src/DbTool/Extensions/DbEntityExtensions.cs index 352aaaa..6b7fdb9 100644 --- a/src/DbTool/Extensions/DbEntityExtensions.cs +++ b/src/DbTool/Extensions/DbEntityExtensions.cs @@ -1,16 +1,18 @@ -using DbTool.Core.Entity; +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + +using DbTool.Core.Entity; // ReSharper disable once CheckNamespace -namespace DbTool +namespace DbTool; + +public static class DbEntityExtensions { - public static class DbEntityExtensions + public static string GetFullTableName(this TableEntity tableEntity) { - public static string GetFullTableName(this TableEntity tableEntity) - { - var fullName = string.IsNullOrEmpty(tableEntity.TableSchema) - ? tableEntity.TableName - : $"{tableEntity.TableSchema}.{tableEntity.TableName}"; - return fullName; - } + var fullName = string.IsNullOrEmpty(tableEntity.TableSchema) + ? tableEntity.TableName + : $"{tableEntity.TableSchema}.{tableEntity.TableName}"; + return fullName; } } diff --git a/src/DbTool/Extensions/DictionaryExtensions.cs b/src/DbTool/Extensions/DictionaryExtensions.cs index 0c87991..26686c6 100644 --- a/src/DbTool/Extensions/DictionaryExtensions.cs +++ b/src/DbTool/Extensions/DictionaryExtensions.cs @@ -1,16 +1,18 @@ -using System.Collections.Generic; +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + +using System.Collections.Generic; using System.Linq; using WeihanLi.Extensions; // ReSharper disable once CheckNamespace -namespace DbTool +namespace DbTool; + +public static class DictionaryExtensions { - public static class DictionaryExtensions + public static string ToFileChooseFilter(this Dictionary supportedFileExtensions) { - public static string ToFileChooseFilter(this Dictionary supportedFileExtensions) - { - return supportedFileExtensions.Select(x => $"{x.Value}|*{x.Key}") - .StringJoin("|"); - } + return supportedFileExtensions.Select(x => $"{x.Value}|*{x.Key}") + .StringJoin("|"); } } diff --git a/src/DbTool/Localization/LocalizerExtension.cs b/src/DbTool/Localization/LocalizerExtension.cs index afe477b..eed64ce 100644 --- a/src/DbTool/Localization/LocalizerExtension.cs +++ b/src/DbTool/Localization/LocalizerExtension.cs @@ -1,27 +1,29 @@ -using System; -using System.Windows.Markup; +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + using Microsoft.Extensions.Localization; +using System; +using System.Windows.Markup; using WeihanLi.Common; -namespace DbTool.Localization +namespace DbTool.Localization; + +public class LocalizerExtension : MarkupExtension { - public class LocalizerExtension : MarkupExtension - { - private readonly IStringLocalizer _localizer; - public string Key { get; } + private readonly IStringLocalizer _localizer; + public string Key { get; } - public LocalizerExtension(string key) - { - Key = key; - _localizer = DependencyResolver. - ResolveRequiredService() - .Create(typeof(MainWindow)); - } + public LocalizerExtension(string key) + { + Key = key; + _localizer = DependencyResolver. + ResolveRequiredService() + .Create(typeof(MainWindow)); + } - public override object ProvideValue(IServiceProvider serviceProvider) - { - var value = _localizer[Key]; - return (string)value; - } + public override object ProvideValue(IServiceProvider serviceProvider) + { + var value = _localizer[Key]; + return (string)value; } } diff --git a/src/DbTool/MainWindow.xaml.cs b/src/DbTool/MainWindow.xaml.cs index 6be8b4b..9b49fe9 100644 --- a/src/DbTool/MainWindow.xaml.cs +++ b/src/DbTool/MainWindow.xaml.cs @@ -1,4 +1,12 @@ -using System; +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + +using DbTool.Core; +using DbTool.Core.Entity; +using DbTool.ViewModels; +using Microsoft.Extensions.Localization; +using Microsoft.Win32; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -8,508 +16,502 @@ using System.Threading; using System.Windows; using System.Windows.Controls; -using DbTool.Core; -using DbTool.Core.Entity; -using DbTool.ViewModels; -using Microsoft.Extensions.Localization; -using Microsoft.Win32; using WeihanLi.Common; using WeihanLi.Extensions; -namespace DbTool +namespace DbTool; + +/// +/// Interaction logic for MainWindow.xaml +/// +public partial class MainWindow { - /// - /// Interaction logic for MainWindow.xaml - /// - public partial class MainWindow + private readonly IStringLocalizer _localizer; + private readonly DbProviderFactory _dbProviderFactory; + private readonly IDbHelperFactory _dbHelperFactory; + private readonly SettingsViewModel _settings; + + private readonly IModelNameConverter _modelNameConverter; + + public MainWindow( + IStringLocalizer localizer, + DbProviderFactory dbProviderFactory, + IDbHelperFactory dbHelperFactory, + SettingsViewModel settings, + IModelNameConverter modelNameConverter) { - private readonly IStringLocalizer _localizer; - private readonly DbProviderFactory _dbProviderFactory; - private readonly IDbHelperFactory _dbHelperFactory; - private readonly SettingsViewModel _settings; - - private readonly IModelNameConverter _modelNameConverter; - - public MainWindow( - IStringLocalizer localizer, - DbProviderFactory dbProviderFactory, - IDbHelperFactory dbHelperFactory, - SettingsViewModel settings, - IModelNameConverter modelNameConverter) - { - InitializeComponent(); + InitializeComponent(); - _localizer = localizer; - _settings = settings; - _dbProviderFactory = dbProviderFactory; - _dbHelperFactory = dbHelperFactory; - _modelNameConverter = modelNameConverter; + _localizer = localizer; + _settings = settings; + _dbProviderFactory = dbProviderFactory; + _dbHelperFactory = dbHelperFactory; + _modelNameConverter = modelNameConverter; - InitDataBinding(); - } + InitDataBinding(); + } - private void InitDataBinding() + private void InitDataBinding() + { + DataContext = _settings; + + DbFirst_DbType.ItemsSource = _dbProviderFactory.SupportedDbTypes; + DbFirst_DbType.SelectedItem = _settings.DefaultDbType; + + DefaultDbType.ItemsSource = _dbProviderFactory.SupportedDbTypes; + DefaultDbType.SelectedItem = _settings.DefaultDbType; + + var supportedCultures = _settings.SupportedCultures + .Select(c => new CultureInfo(c)) + .ToArray(); + DefaultCulture.ItemsSource = supportedCultures; + DefaultCulture.SelectedItem = supportedCultures.FirstOrDefault(c => c.Name == _settings.DefaultCulture); + + CbGenPrivateFields.IsChecked = _settings.GeneratePrivateField; + CbGenDataAnnotation.IsChecked = _settings.GenerateDataAnnotation; + CbGlobalUsing.IsChecked = cbGlobalUsingSetting.IsChecked = _settings.GlobalUsingEnabled; + CbNullableReferenceTypes.IsChecked = cbNullableReferenceTypesSetting.IsChecked = _settings.NullableReferenceTypesEnabled; + CbFileScopedNamespace.IsChecked = cbFileScopedNamespaceSetting.IsChecked = _settings.FileScopedNamespaceEnabled; + CodeGenDbDescCheckBox.IsChecked = _settings.GenerateDbDescription; + ModelFirstGenDesc.IsChecked = _settings.GenerateDbDescription; + + var codeGenerators = DependencyResolver.ResolveServices(); + foreach (var generator in codeGenerators) { - DataContext = _settings; - - DbFirst_DbType.ItemsSource = _dbProviderFactory.SupportedDbTypes; - DbFirst_DbType.SelectedItem = _settings.DefaultDbType; - - DefaultDbType.ItemsSource = _dbProviderFactory.SupportedDbTypes; - DefaultDbType.SelectedItem = _settings.DefaultDbType; - - var supportedCultures = _settings.SupportedCultures - .Select(c => new CultureInfo(c)) - .ToArray(); - DefaultCulture.ItemsSource = supportedCultures; - DefaultCulture.SelectedItem = supportedCultures.FirstOrDefault(c => c.Name == _settings.DefaultCulture); - - CbGenPrivateFields.IsChecked = _settings.GeneratePrivateField; - CbGenDataAnnotation.IsChecked = _settings.GenerateDataAnnotation; - CbGlobalUsing.IsChecked = cbGlobalUsingSetting.IsChecked = _settings.GlobalUsingEnabled; - CbNullableReferenceTypes.IsChecked = cbNullableReferenceTypesSetting.IsChecked = _settings.NullableReferenceTypesEnabled; - CbFileScopedNamespace.IsChecked = cbFileScopedNamespaceSetting.IsChecked = _settings.FileScopedNamespaceEnabled; - CodeGenDbDescCheckBox.IsChecked = _settings.GenerateDbDescription; - ModelFirstGenDesc.IsChecked = _settings.GenerateDbDescription; - - var codeGenerators = DependencyResolver.ResolveServices(); - foreach (var generator in codeGenerators) + var button = new Button() { - var button = new Button() - { - Content = $"{_localizer["Export"]} {generator.CodeType} Code", - Tag = generator, - MaxWidth = 180, - Margin = new Thickness(4) - }; - button.Click += ExportModel_Click; - ModelCodeGeneratorsPanel.Children.Add(button); - } - var exporters = DependencyResolver.ResolveServices(); - foreach (var exporter in exporters) - { - var exportButton = new Button() - { - Content = $"{_localizer["Export"]}{exporter.ExportType}", - Tag = exporter, - MaxWidth = 180, - Margin = new Thickness(4) - }; - exportButton.Click += ExportButton_Click; - DbDocExportersPanel.Children.Add(exportButton); - } - var importers = DependencyResolver.ResolveServices(); - foreach (var importer in importers) + Content = $"{_localizer["Export"]} {generator.CodeType} Code", + Tag = generator, + MaxWidth = 180, + Margin = new Thickness(4) + }; + button.Click += ExportModel_Click; + ModelCodeGeneratorsPanel.Children.Add(button); + } + var exporters = DependencyResolver.ResolveServices(); + foreach (var exporter in exporters) + { + var exportButton = new Button() { - var importButton = new Button() - { - Content = $"{_localizer["ChooseFile"]}({importer.ImportType})", - Tag = importer, - MaxWidth = 160, - Margin = new Thickness(4, 0, 4, 0) - }; - importButton.Click += ImportButton_Click; - DbDocImportersPanel.Children.Add(importButton); - } - var codeExtractors = DependencyResolver.ResolveServices(); - foreach (var extractor in codeExtractors) + Content = $"{_localizer["Export"]}{exporter.ExportType}", + Tag = exporter, + MaxWidth = 180, + Margin = new Thickness(4) + }; + exportButton.Click += ExportButton_Click; + DbDocExportersPanel.Children.Add(exportButton); + } + var importers = DependencyResolver.ResolveServices(); + foreach (var importer in importers) + { + var importButton = new Button() { - var button = new Button() - { - Content = $"{_localizer["ChooseModelFiles"]}({extractor.CodeType})", - Margin = new Thickness(8), - Tag = extractor, - MaxWidth = 300 - }; - button.Click += ChooseModel_Click; - CodeExtractorsPannel.Children.Add(button); - } + Content = $"{_localizer["ChooseFile"]}({importer.ImportType})", + Tag = importer, + MaxWidth = 160, + Margin = new Thickness(4, 0, 4, 0) + }; + importButton.Click += ImportButton_Click; + DbDocImportersPanel.Children.Add(importButton); } - - private void ExportModel_Click(object sender, RoutedEventArgs e) + var codeExtractors = DependencyResolver.ResolveServices(); + foreach (var extractor in codeExtractors) { - if (sender is Button { Tag: IModelCodeGenerator codeGenerator }) + var button = new Button() { - if (CheckedTables.SelectedItems.Count == 0) - { - MessageBox.Show(_localizer["ChooseTables"]); - return; - } - var options = new ModelCodeGenerateOptions() - { - Namespace = TxtNamespace.Text.GetValueOrDefault("Models"), - Prefix = TxtPrefix.Text, - Suffix = TxtSuffix.Text, - GenerateDataAnnotation = CbGenDataAnnotation.IsChecked == true, - GeneratePrivateFields = CbGenPrivateFields.IsChecked == true, - GlobalUsingEnabled = CbGlobalUsing.IsChecked == true, - NullableReferenceTypesEnabled = CbNullableReferenceTypes.IsChecked == true, - FileScopedNamespaceEnabled = CbFileScopedNamespace.IsChecked == true, - Indentation = " " - }; - var dir = ChooseFolder(); - if (string.IsNullOrEmpty(dir)) - { - return; - } - foreach (var item in CheckedTables.SelectedItems) - { - if (item is TableEntity table) - { - var modelCode = codeGenerator.GenerateModelCode(table, options, _dbProviderFactory.GetDbProvider(_dbHelper?.DbType ?? _settings.DefaultDbType)); - var path = Path.Combine(dir, $"{ _modelNameConverter.ConvertTableToModel(table.TableName ?? "")}{codeGenerator.FileExtension}"); - File.WriteAllText(path, modelCode, Encoding.UTF8); - } - } - // open dir - Process.Start("Explorer.exe", dir); - } + Content = $"{_localizer["ChooseModelFiles"]}({extractor.CodeType})", + Margin = new Thickness(8), + Tag = extractor, + MaxWidth = 300 + }; + button.Click += ChooseModel_Click; + CodeExtractorsPannel.Children.Add(button); } + } - private void ExportButton_Click(object sender, RoutedEventArgs e) + private void ExportModel_Click(object sender, RoutedEventArgs e) + { + if (sender is Button { Tag: IModelCodeGenerator codeGenerator }) { - if (_dbHelper is null) + if (CheckedTables.SelectedItems.Count == 0) { - MessageBox.Show(_localizer["DbNotConnected"]); + MessageBox.Show(_localizer["ChooseTables"]); return; } - if (CheckedTables.SelectedItems.Count == 0) + var options = new ModelCodeGenerateOptions() + { + Namespace = TxtNamespace.Text.GetValueOrDefault("Models"), + Prefix = TxtPrefix.Text, + Suffix = TxtSuffix.Text, + GenerateDataAnnotation = CbGenDataAnnotation.IsChecked == true, + GeneratePrivateFields = CbGenPrivateFields.IsChecked == true, + GlobalUsingEnabled = CbGlobalUsing.IsChecked == true, + NullableReferenceTypesEnabled = CbNullableReferenceTypes.IsChecked == true, + FileScopedNamespaceEnabled = CbFileScopedNamespace.IsChecked == true, + Indentation = " " + }; + var dir = ChooseFolder(); + if (string.IsNullOrEmpty(dir)) { - MessageBox.Show(_localizer["ChooseTables"], _localizer["Tip"]); return; } - - if (sender is Button { Tag: IDbDocExporter exporter }) + foreach (var item in CheckedTables.SelectedItems) { - var tables = new List(); - foreach (var item in CheckedTables.SelectedItems) + if (item is TableEntity table) { - if (item is TableEntity table) - { - tables.Add(table); - } + var modelCode = codeGenerator.GenerateModelCode(table, options, _dbProviderFactory.GetDbProvider(_dbHelper?.DbType ?? _settings.DefaultDbType)); + var path = Path.Combine(dir, $"{ _modelNameConverter.ConvertTableToModel(table.TableName ?? "")}{codeGenerator.FileExtension}"); + File.WriteAllText(path, modelCode, Encoding.UTF8); } - if (tables.Count == 0) return; + } + // open dir + Process.Start("Explorer.exe", dir); + } + } + + private void ExportButton_Click(object sender, RoutedEventArgs e) + { + if (_dbHelper is null) + { + MessageBox.Show(_localizer["DbNotConnected"]); + return; + } + if (CheckedTables.SelectedItems.Count == 0) + { + MessageBox.Show(_localizer["ChooseTables"], _localizer["Tip"]); + return; + } - var dir = ChooseFolder(); - if (string.IsNullOrEmpty(dir)) + if (sender is Button { Tag: IDbDocExporter exporter }) + { + var tables = new List(); + foreach (var item in CheckedTables.SelectedItems) + { + if (item is TableEntity table) { - return; + tables.Add(table); } - try - { - var exportBytes = exporter.Export(tables.ToArray(), _dbProviderFactory.GetDbProvider(_dbHelper.DbType)); - if (exportBytes.Length > 0) - { - var fileName = tables.Count > 1 - ? _dbHelper.DatabaseName - : - _settings.GlobalUsingEnabled - ? _modelNameConverter.ConvertTableToModel(tables[0].TableName) - : tables[0].TableName - ; - fileName = $"{fileName}.{exporter.FileExtension.TrimStart('.')}"; - var path = Path.Combine(dir, fileName); - File.WriteAllBytes(path, exportBytes); - // open dir - Process.Start("Explorer.exe", dir); - } - } - catch (Exception exception) + } + if (tables.Count == 0) return; + + var dir = ChooseFolder(); + if (string.IsNullOrEmpty(dir)) + { + return; + } + try + { + var exportBytes = exporter.Export(tables.ToArray(), _dbProviderFactory.GetDbProvider(_dbHelper.DbType)); + if (exportBytes.Length > 0) { - MessageBox.Show(exception.ToString(), "Export Error"); + var fileName = tables.Count > 1 + ? _dbHelper.DatabaseName + : + _settings.GlobalUsingEnabled + ? _modelNameConverter.ConvertTableToModel(tables[0].TableName) + : tables[0].TableName + ; + fileName = $"{fileName}.{exporter.FileExtension.TrimStart('.')}"; + var path = Path.Combine(dir, fileName); + File.WriteAllBytes(path, exportBytes); + // open dir + Process.Start("Explorer.exe", dir); } } + catch (Exception exception) + { + MessageBox.Show(exception.ToString(), "Export Error"); + } } + } - private void ImportButton_Click(object sender, RoutedEventArgs e) + private void ImportButton_Click(object sender, RoutedEventArgs e) + { + if (sender is Button { Tag: IDbDocImporter importer }) { - if (sender is Button { Tag: IDbDocImporter importer }) + var ofg = new OpenFileDialog { - var ofg = new OpenFileDialog - { - Multiselect = false, - CheckFileExists = true, - Filter = importer.SupportedFileExtensions.ToFileChooseFilter() - }; - if (ofg.ShowDialog() == true) + Multiselect = false, + CheckFileExists = true, + Filter = importer.SupportedFileExtensions.ToFileChooseFilter() + }; + if (ofg.ShowDialog() == true) + { + try { - try + var dbProvider = _dbProviderFactory.GetDbProvider(_settings.DefaultDbType); + var tables = importer.Import(ofg.FileName, dbProvider); + + if (tables.Length > 0) { - var dbProvider = _dbProviderFactory.GetDbProvider(_settings.DefaultDbType); - var tables = importer.Import(ofg.FileName, dbProvider); + TxtModelFirstTableName.Text = tables[0].TableName; + TxtModelFirstTableDesc.Text = tables[0].TableDescription; + ModelDataGrid.ItemsSource = tables[0].Columns; - if (tables.Length > 0) + var sbSqlText = new StringBuilder(); + foreach (var table in tables) { - TxtModelFirstTableName.Text = tables[0].TableName; - TxtModelFirstTableDesc.Text = tables[0].TableDescription; - ModelDataGrid.ItemsSource = tables[0].Columns; - - var sbSqlText = new StringBuilder(); - foreach (var table in tables) - { - sbSqlText.AppendLine(dbProvider.GenerateSqlStatement(table, ModelFirstGenDesc.IsChecked == true)); - } - var sql = sbSqlText.ToString(); - TxtModelFirstGeneratedSql.Text = sql; - Clipboard.SetText(sql); - MessageBox.Show(_localizer["SqlCopiedToClipboard"], _localizer["Tip"]); + sbSqlText.AppendLine(dbProvider.GenerateSqlStatement(table, ModelFirstGenDesc.IsChecked == true)); } + var sql = sbSqlText.ToString(); + TxtModelFirstGeneratedSql.Text = sql; + Clipboard.SetText(sql); + MessageBox.Show(_localizer["SqlCopiedToClipboard"], _localizer["Tip"]); } - catch (Exception ex) - { - MessageBox.Show(ex.ToString(), "Error"); - } + } + catch (Exception ex) + { + MessageBox.Show(ex.ToString(), "Error"); } } } + } - private async void ChooseModel_Click(object sender, RoutedEventArgs e) + private async void ChooseModel_Click(object sender, RoutedEventArgs e) + { + if (sender is Button { Tag: IModelCodeExtractor extractor }) { - if (sender is Button { Tag: IModelCodeExtractor extractor }) + var ofg = new OpenFileDialog { - var ofg = new OpenFileDialog - { - CheckFileExists = true, - Multiselect = true, - Filter = extractor.SupportedFileExtensions.ToFileChooseFilter() - }; - if (ofg.ShowDialog() == true) + CheckFileExists = true, + Multiselect = true, + Filter = extractor.SupportedFileExtensions.ToFileChooseFilter() + }; + if (ofg.ShowDialog() == true) + { + try { - try + var dbProvider = _dbProviderFactory.GetDbProvider(_settings.DefaultDbType); + var tables = await extractor.GetTablesFromSourceFiles(dbProvider, ofg.FileNames); + if (tables.Count == 0) { - var dbProvider = _dbProviderFactory.GetDbProvider(_settings.DefaultDbType); - var tables = await extractor.GetTablesFromSourceFiles(dbProvider, ofg.FileNames); - if (tables.Count == 0) - { - MessageBox.Show(_localizer["NoModelFound"]); - } - else - { - TxtCodeGenSql.Clear(); - foreach (var table in tables) - { - var tableSql = dbProvider.GenerateSqlStatement(table, CodeGenDbDescCheckBox.IsChecked == true); - TxtCodeGenSql.AppendText(tableSql); - TxtCodeGenSql.AppendText(Environment.NewLine); - } - CodeGenTableTreeView.ItemsSource = tables; - } + MessageBox.Show(_localizer["NoModelFound"]); } - catch (Exception ex) + else { - MessageBox.Show(ex.Message, "Error"); + TxtCodeGenSql.Clear(); + foreach (var table in tables) + { + var tableSql = dbProvider.GenerateSqlStatement(table, CodeGenDbDescCheckBox.IsChecked == true); + TxtCodeGenSql.AppendText(tableSql); + TxtCodeGenSql.AppendText(Environment.NewLine); + } + CodeGenTableTreeView.ItemsSource = tables; } } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Error"); + } } } + } - private void BtnSaveSettings_OnClick(object sender, RoutedEventArgs e) + private void BtnSaveSettings_OnClick(object sender, RoutedEventArgs e) + { + if (null != DefaultDbType.SelectedItem && _settings.DefaultDbType != DefaultDbType.SelectedItem.ToString()) { - if (null != DefaultDbType.SelectedItem && _settings.DefaultDbType != DefaultDbType.SelectedItem.ToString()) - { - _settings.DefaultDbType = DefaultDbType.SelectedItem?.ToString() ?? string.Empty; - } - if (DefaultCulture.SelectedItem is CultureInfo culture && culture.Name != _settings.DefaultCulture) - { - _settings.DefaultCulture = culture.Name; - Thread.CurrentThread.CurrentCulture = culture; - Thread.CurrentThread.CurrentUICulture = culture; - } - if (_settings.DefaultConnectionString != TxtDefaultConnStr.Text.Trim()) - { - _settings.DefaultConnectionString = TxtDefaultConnStr.Text.Trim(); - } - - _settings.GlobalUsingEnabled = cbGlobalUsingSetting.IsChecked != false; - _settings.NullableReferenceTypesEnabled = cbNullableReferenceTypesSetting.IsChecked != false; - _settings.FileScopedNamespaceEnabled = cbFileScopedNamespaceSetting.IsChecked != false; - MessageBox.Show(_localizer["Success"], _localizer["Tip"]); + _settings.DefaultDbType = DefaultDbType.SelectedItem?.ToString() ?? string.Empty; + } + if (DefaultCulture.SelectedItem is CultureInfo culture && culture.Name != _settings.DefaultCulture) + { + _settings.DefaultCulture = culture.Name; + Thread.CurrentThread.CurrentCulture = culture; + Thread.CurrentThread.CurrentUICulture = culture; } + if (_settings.DefaultConnectionString != TxtDefaultConnStr.Text.Trim()) + { + _settings.DefaultConnectionString = TxtDefaultConnStr.Text.Trim(); + } + + _settings.GlobalUsingEnabled = cbGlobalUsingSetting.IsChecked != false; + _settings.NullableReferenceTypesEnabled = cbNullableReferenceTypesSetting.IsChecked != false; + _settings.FileScopedNamespaceEnabled = cbFileScopedNamespaceSetting.IsChecked != false; + MessageBox.Show(_localizer["Success"], _localizer["Tip"]); + } - private void BtnGenerateSql_OnClick(object sender, RoutedEventArgs e) + private void BtnGenerateSql_OnClick(object sender, RoutedEventArgs e) + { + if (ModelDataGrid.Items.Count > 0) { - if (ModelDataGrid.Items.Count > 0) + if (string.IsNullOrEmpty(TxtModelFirstTableName.Text)) { - if (string.IsNullOrEmpty(TxtModelFirstTableName.Text)) - { - return; - } + return; + } - var table = new TableEntity() - { - TableName = TxtModelFirstTableName.Text, - TableDescription = TxtModelFirstTableDesc.Text, - }; - foreach (var item in ModelDataGrid.Items) + var table = new TableEntity() + { + TableName = TxtModelFirstTableName.Text, + TableDescription = TxtModelFirstTableDesc.Text, + }; + foreach (var item in ModelDataGrid.Items) + { + if (item is ColumnEntity column && !string.IsNullOrEmpty(column.ColumnName)) { - if (item is ColumnEntity column && !string.IsNullOrEmpty(column.ColumnName)) - { - table.Columns.Add(column); - } + table.Columns.Add(column); } - var dbProvider = _dbProviderFactory.GetDbProvider(_settings.DefaultDbType); - var sql = dbProvider.GenerateSqlStatement(table, ModelFirstGenDesc.IsChecked == true); - TxtModelFirstGeneratedSql.Text = sql; - Clipboard.SetText(sql); - MessageBox.Show(_localizer["SqlCopiedToClipboard"], _localizer["Tip"]); } + var dbProvider = _dbProviderFactory.GetDbProvider(_settings.DefaultDbType); + var sql = dbProvider.GenerateSqlStatement(table, ModelFirstGenDesc.IsChecked == true); + TxtModelFirstGeneratedSql.Text = sql; + Clipboard.SetText(sql); + MessageBox.Show(_localizer["SqlCopiedToClipboard"], _localizer["Tip"]); } + } - private void DownloadExcelTemplateLink_OnClick(object sender, RoutedEventArgs e) + private void DownloadExcelTemplateLink_OnClick(object sender, RoutedEventArgs e) + { + // https://stackoverflow.com/questions/59716856/net-core-3-1-process-startwww-website-com-not-working-in-wpf + Process.Start(new ProcessStartInfo(_settings.ExcelTemplateDownloadLink) { - // https://stackoverflow.com/questions/59716856/net-core-3-1-process-startwww-website-com-not-working-in-wpf - Process.Start(new ProcessStartInfo(_settings.ExcelTemplateDownloadLink) - { - UseShellExecute = true - }); - } + UseShellExecute = true + }); + } - private IDbHelper? _dbHelper; + private IDbHelper? _dbHelper; - private async void BtnConnectDb_OnClick(object sender, RoutedEventArgs e) + private async void BtnConnectDb_OnClick(object sender, RoutedEventArgs e) + { + if (string.IsNullOrEmpty(TxtConnectionString.Text)) { - if (string.IsNullOrEmpty(TxtConnectionString.Text)) - { - MessageBox.Show(_localizer["ConnectionStringCannotBeEmpty"]); - return; - } - try - { - var connStr = TxtConnectionString.Text; - var dbProvider = _dbProviderFactory.GetDbProvider(DbFirst_DbType.SelectedItem?.ToString() ?? _settings.DefaultDbType); - _dbHelper = _dbHelperFactory.GetDbHelper(dbProvider, connStr); + MessageBox.Show(_localizer["ConnectionStringCannotBeEmpty"]); + return; + } + try + { + var connStr = TxtConnectionString.Text; + var dbProvider = _dbProviderFactory.GetDbProvider(DbFirst_DbType.SelectedItem?.ToString() ?? _settings.DefaultDbType); + _dbHelper = _dbHelperFactory.GetDbHelper(dbProvider, connStr); - var tables = await _dbHelper.GetTablesInfoAsync(); - CheckedTables.Dispatcher.Invoke(() => - { - CheckedTables.ItemsSource = tables - .Select(t => new CheckableTableEntity - { - TableName = t.TableName, - TableDescription = t.TableDescription, - TableSchema = t.TableSchema, - Columns = t.Columns - }) - .OrderBy(x => x.GetFullTableName()) - .ToArray(); - }); - } - catch (Exception exception) + var tables = await _dbHelper.GetTablesInfoAsync(); + CheckedTables.Dispatcher.Invoke(() => { - MessageBox.Show(exception.ToString(), "Error"); - } + CheckedTables.ItemsSource = tables + .Select(t => new CheckableTableEntity + { + TableName = t.TableName, + TableDescription = t.TableDescription, + TableSchema = t.TableSchema, + Columns = t.Columns + }) + .OrderBy(x => x.GetFullTableName()) + .ToArray(); + }); } + catch (Exception exception) + { + MessageBox.Show(exception.ToString(), "Error"); + } + } - private string? ChooseFolder() + private string? ChooseFolder() + { + var dialog = new System.Windows.Forms.FolderBrowserDialog { - var dialog = new System.Windows.Forms.FolderBrowserDialog - { - Description = _localizer["ChooseDirTip"], - ShowNewFolderButton = true - }; - if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) - { - return dialog.SelectedPath; - } - return null; + Description = _localizer["ChooseDirTip"], + ShowNewFolderButton = true + }; + if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) + { + return dialog.SelectedPath; } + return null; + } - protected override void OnClosed(EventArgs e) + protected override void OnClosed(EventArgs e) + { + if (_dbHelper is IDisposable disposable) { - if (_dbHelper is IDisposable disposable) - { - disposable.Dispose(); - } - base.OnClosed(e); + disposable.Dispose(); } + base.OnClosed(e); + } - private async void CheckTableToggled(object sender, RoutedEventArgs e) + private async void CheckTableToggled(object sender, RoutedEventArgs e) + { + if (_dbHelper is null) { - if (_dbHelper is null) - { - MessageBox.Show(_localizer["DbNotConnected"]); - return; - } - if (_selectAllHandling) - return; - if (sender is CheckBox { DataContext: TableEntity table } checkBox) + MessageBox.Show(_localizer["DbNotConnected"]); + return; + } + if (_selectAllHandling) + return; + if (sender is CheckBox { DataContext: TableEntity table } checkBox) + { + if (checkBox.IsChecked == true) { - if (checkBox.IsChecked == true) + if (CheckedTables.SelectedItems.Contains(table) == false) { - if (CheckedTables.SelectedItems.Contains(table) == false) - { - CheckedTables.SelectedItems.Add(table); - } + CheckedTables.SelectedItems.Add(table); + } - if (table.TableName != CurrentCheckedTableName.Text) + if (table.TableName != CurrentCheckedTableName.Text) + { + CurrentCheckedTableName.Text = table.TableName; + if (table.Columns.Count == 0) { - CurrentCheckedTableName.Text = table.TableName; - if (table.Columns.Count == 0) - { - table.Columns = await _dbHelper.GetColumnsInfoAsync(table.TableName); - ColumnListView.Dispatcher.Invoke(() => - { - ColumnListView.ItemsSource = table.Columns; - }); - } - else + table.Columns = await _dbHelper.GetColumnsInfoAsync(table.TableName); + ColumnListView.Dispatcher.Invoke(() => { ColumnListView.ItemsSource = table.Columns; - } + }); } - } - else - { - if (CheckedTables.SelectedItems.Contains(table)) + else { - CheckedTables.SelectedItems.Remove(table); + ColumnListView.ItemsSource = table.Columns; } } } + else + { + if (CheckedTables.SelectedItems.Contains(table)) + { + CheckedTables.SelectedItems.Remove(table); + } + } } + } - private volatile bool _selectAllHandling; + private volatile bool _selectAllHandling; - private void btnSelectAllTables_Click(object sender, RoutedEventArgs e) + private void btnSelectAllTables_Click(object sender, RoutedEventArgs e) + { + if (_dbHelper is null) { - if (_dbHelper is null) - { - MessageBox.Show(_localizer["DbNotConnected"]); - return; - } + MessageBox.Show(_localizer["DbNotConnected"]); + return; + } - if (CheckedTables.ItemsSource is IList tables && tables.Count > 0) - { - _selectAllHandling = true; + if (CheckedTables.ItemsSource is IList tables && tables.Count > 0) + { + _selectAllHandling = true; - try + try + { + if (CheckedTables.SelectedItems.Count == tables.Count) { - if (CheckedTables.SelectedItems.Count == tables.Count) + // uncheck + CheckedTables.SelectedItems.Clear(); + foreach (var item in tables) { - // uncheck - CheckedTables.SelectedItems.Clear(); - foreach (var item in tables) - { - item.Checked = false; - } - } - else - { - // check - CheckedTables.SelectedItems.Clear(); - foreach (var item in tables) - { - CheckedTables.SelectedItems.Add(item); - item.Checked = true; - } + item.Checked = false; } } - finally + else { - _selectAllHandling = false; + // check + CheckedTables.SelectedItems.Clear(); + foreach (var item in tables) + { + CheckedTables.SelectedItems.Add(item); + item.Checked = true; + } } } + finally + { + _selectAllHandling = false; + } } } } diff --git a/src/DbTool/Services/ModelNameConverter.cs b/src/DbTool/Services/ModelNameConverter.cs index 86faf20..2c8037b 100644 --- a/src/DbTool/Services/ModelNameConverter.cs +++ b/src/DbTool/Services/ModelNameConverter.cs @@ -1,33 +1,35 @@ -using System; -using System.Linq; +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + using DbTool.Core; +using System; +using System.Linq; using WeihanLi.Common.Helpers; using WeihanLi.Extensions; // ReSharper disable once CheckNamespace -namespace DbTool +namespace DbTool; + +public sealed class ModelNameConverter : DefaultModelNameConverter { - public sealed class ModelNameConverter : DefaultModelNameConverter + public override string ConvertTableToModel(string tableName) { - public override string ConvertTableToModel(string tableName) - { - var modelName = tableName?.Trim(); - if (modelName.IsNullOrEmpty()) - return string.Empty; + var modelName = tableName?.Trim(); + if (modelName.IsNullOrEmpty()) + return string.Empty; - if (modelName.StartsWith("tab_", StringComparison.OrdinalIgnoreCase) - || modelName.StartsWith("tbl_", StringComparison.OrdinalIgnoreCase)) - modelName = modelName[4..]; + if (modelName.StartsWith("tab_", StringComparison.OrdinalIgnoreCase) + || modelName.StartsWith("tbl_", StringComparison.OrdinalIgnoreCase)) + modelName = modelName[4..]; - if (modelName.StartsWith("tab", StringComparison.OrdinalIgnoreCase) - || modelName.StartsWith("tbl", StringComparison.OrdinalIgnoreCase)) - modelName = modelName[3..]; + if (modelName.StartsWith("tab", StringComparison.OrdinalIgnoreCase) + || modelName.StartsWith("tbl", StringComparison.OrdinalIgnoreCase)) + modelName = modelName[3..]; - modelName = modelName.Split(new[] { '-', '_' }, StringSplitOptions.RemoveEmptyEntries) - .Select(StringHelper.ToPascalCase) - .StringJoin(""); + modelName = modelName.Split(new[] { '-', '_' }, StringSplitOptions.RemoveEmptyEntries) + .Select(StringHelper.ToPascalCase) + .StringJoin(""); - return modelName; - } + return modelName; } } diff --git a/src/DbTool/ViewModels/CheckableTableEntity.cs b/src/DbTool/ViewModels/CheckableTableEntity.cs index cb0868f..0ef91ee 100644 --- a/src/DbTool/ViewModels/CheckableTableEntity.cs +++ b/src/DbTool/ViewModels/CheckableTableEntity.cs @@ -1,29 +1,31 @@ -using System.ComponentModel; -using System.Runtime.CompilerServices; +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + using DbTool.Core.Entity; +using System.ComponentModel; +using System.Runtime.CompilerServices; -namespace DbTool.ViewModels +namespace DbTool.ViewModels; + +public class CheckableTableEntity : TableEntity, INotifyPropertyChanged { - public class CheckableTableEntity : TableEntity, INotifyPropertyChanged - { - private bool _checked; + private bool _checked; - public bool Checked + public bool Checked + { + get => _checked; + set { - get => _checked; - set - { - _checked = value; - NotifyPropertyChanged(); - } + _checked = value; + NotifyPropertyChanged(); } + } - public event PropertyChangedEventHandler? PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; - public void NotifyPropertyChanged([CallerMemberName] string? propertyName = null) - { - if (PropertyChanged != null) - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } + public void NotifyPropertyChanged([CallerMemberName] string? propertyName = null) + { + if (PropertyChanged != null) + PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } diff --git a/src/DbTool/ViewModels/SettingsViewModel.cs b/src/DbTool/ViewModels/SettingsViewModel.cs index 0fb1b3a..94e091f 100644 --- a/src/DbTool/ViewModels/SettingsViewModel.cs +++ b/src/DbTool/ViewModels/SettingsViewModel.cs @@ -1,142 +1,144 @@ -using System; +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. -namespace DbTool.ViewModels +using System; + +namespace DbTool.ViewModels; + +public class SettingsViewModel { - public class SettingsViewModel + private string _defaultDbType; + private string _defaultConnectionString; + private bool _generatePrivateField; + private bool _generateDataAnnotation; + private string _excelTemplateDownloadLink; + private string _defaultCulture; + private bool _generateDbDescription; + private bool _globalUsingEnabled; + private bool _nullableReferenceTypesEnabled; + private bool _fileScopedNamespaceEnabled; + + public SettingsViewModel() { - private string _defaultDbType; - private string _defaultConnectionString; - private bool _generatePrivateField; - private bool _generateDataAnnotation; - private string _excelTemplateDownloadLink; - private string _defaultCulture; - private bool _generateDbDescription; - private bool _globalUsingEnabled; - private bool _nullableReferenceTypesEnabled; - private bool _fileScopedNamespaceEnabled; - - public SettingsViewModel() - { - _excelTemplateDownloadLink = - ConfigurationHelper.AppSetting(ConfigurationConstants.ExcelTemplateDownloadLink); - _defaultConnectionString = ConfigurationHelper.AppSetting(ConfigurationConstants.DefaultConnectionString); - _defaultDbType = ConfigurationHelper.AppSetting(ConfigurationConstants.DbType); - _generateDataAnnotation = - ConfigurationHelper.AppSetting(ConfigurationConstants.GenerateDataAnnotation); - _generatePrivateField = ConfigurationHelper.AppSetting(ConfigurationConstants.GeneratePrivateField); - _generateDbDescription = ConfigurationHelper.AppSetting(ConfigurationConstants.GenerateDbDescription); - _globalUsingEnabled = ConfigurationHelper.AppSetting(nameof(GlobalUsingEnabled)); - _nullableReferenceTypesEnabled = ConfigurationHelper.AppSetting(nameof(NullableReferenceTypesEnabled)); - _fileScopedNamespaceEnabled = ConfigurationHelper.AppSetting(nameof(FileScopedNamespaceEnabled)); - _defaultCulture = ConfigurationHelper.AppSetting(nameof(DefaultCulture)); - SupportedCultures = ConfigurationHelper.AppSetting(nameof(SupportedCultures)) - .Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); - - ConnectionString = _defaultConnectionString; - } + _excelTemplateDownloadLink = + ConfigurationHelper.AppSetting(ConfigurationConstants.ExcelTemplateDownloadLink); + _defaultConnectionString = ConfigurationHelper.AppSetting(ConfigurationConstants.DefaultConnectionString); + _defaultDbType = ConfigurationHelper.AppSetting(ConfigurationConstants.DbType); + _generateDataAnnotation = + ConfigurationHelper.AppSetting(ConfigurationConstants.GenerateDataAnnotation); + _generatePrivateField = ConfigurationHelper.AppSetting(ConfigurationConstants.GeneratePrivateField); + _generateDbDescription = ConfigurationHelper.AppSetting(ConfigurationConstants.GenerateDbDescription); + _globalUsingEnabled = ConfigurationHelper.AppSetting(nameof(GlobalUsingEnabled)); + _nullableReferenceTypesEnabled = ConfigurationHelper.AppSetting(nameof(NullableReferenceTypesEnabled)); + _fileScopedNamespaceEnabled = ConfigurationHelper.AppSetting(nameof(FileScopedNamespaceEnabled)); + _defaultCulture = ConfigurationHelper.AppSetting(nameof(DefaultCulture)); + SupportedCultures = ConfigurationHelper.AppSetting(nameof(SupportedCultures)) + .Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); + + ConnectionString = _defaultConnectionString; + } - public string DefaultDbType + public string DefaultDbType + { + get => _defaultDbType; + set { - get => _defaultDbType; - set - { - _defaultDbType = value; - ConfigurationHelper.UpdateAppSetting(ConfigurationConstants.DbType, value); - } + _defaultDbType = value; + ConfigurationHelper.UpdateAppSetting(ConfigurationConstants.DbType, value); } + } - public string DefaultConnectionString + public string DefaultConnectionString + { + get => _defaultConnectionString; + set { - get => _defaultConnectionString; - set - { - _defaultConnectionString = value; - ConfigurationHelper.UpdateAppSetting(ConfigurationConstants.DefaultConnectionString, value); - } + _defaultConnectionString = value; + ConfigurationHelper.UpdateAppSetting(ConfigurationConstants.DefaultConnectionString, value); } + } - public string ConnectionString { get; set; } + public string ConnectionString { get; set; } - public bool GeneratePrivateField + public bool GeneratePrivateField + { + get => _generatePrivateField; + set { - get => _generatePrivateField; - set - { - _generatePrivateField = value; - ConfigurationHelper.UpdateAppSetting(ConfigurationConstants.GeneratePrivateField, value); - } + _generatePrivateField = value; + ConfigurationHelper.UpdateAppSetting(ConfigurationConstants.GeneratePrivateField, value); } + } - public bool GenerateDataAnnotation + public bool GenerateDataAnnotation + { + get => _generateDataAnnotation; + set { - get => _generateDataAnnotation; - set - { - _generateDataAnnotation = value; - ConfigurationHelper.UpdateAppSetting(ConfigurationConstants.GenerateDataAnnotation, value); - } + _generateDataAnnotation = value; + ConfigurationHelper.UpdateAppSetting(ConfigurationConstants.GenerateDataAnnotation, value); } + } - public bool GenerateDbDescription + public bool GenerateDbDescription + { + get => _generateDbDescription; + set { - get => _generateDbDescription; - set - { - _generateDbDescription = value; - ConfigurationHelper.UpdateAppSetting(nameof(GenerateDbDescription), value); - } + _generateDbDescription = value; + ConfigurationHelper.UpdateAppSetting(nameof(GenerateDbDescription), value); } + } - public bool GlobalUsingEnabled + public bool GlobalUsingEnabled + { + get => _globalUsingEnabled; + set { - get => _globalUsingEnabled; - set - { - _globalUsingEnabled = value; - ConfigurationHelper.UpdateAppSetting(nameof(GlobalUsingEnabled), value); - } + _globalUsingEnabled = value; + ConfigurationHelper.UpdateAppSetting(nameof(GlobalUsingEnabled), value); } + } - public bool NullableReferenceTypesEnabled + public bool NullableReferenceTypesEnabled + { + get => _nullableReferenceTypesEnabled; + set { - get => _nullableReferenceTypesEnabled; - set - { - _nullableReferenceTypesEnabled = value; - ConfigurationHelper.UpdateAppSetting(nameof(NullableReferenceTypesEnabled), value); - } + _nullableReferenceTypesEnabled = value; + ConfigurationHelper.UpdateAppSetting(nameof(NullableReferenceTypesEnabled), value); } + } - public bool FileScopedNamespaceEnabled + public bool FileScopedNamespaceEnabled + { + get => _fileScopedNamespaceEnabled; + set { - get => _fileScopedNamespaceEnabled; - set - { - _fileScopedNamespaceEnabled = value; - ConfigurationHelper.UpdateAppSetting(nameof(FileScopedNamespaceEnabled), value); - } + _fileScopedNamespaceEnabled = value; + ConfigurationHelper.UpdateAppSetting(nameof(FileScopedNamespaceEnabled), value); } + } - public string ExcelTemplateDownloadLink + public string ExcelTemplateDownloadLink + { + get => _excelTemplateDownloadLink; + set { - get => _excelTemplateDownloadLink; - set - { - _excelTemplateDownloadLink = value; - ConfigurationHelper.UpdateAppSetting(ConfigurationConstants.ExcelTemplateDownloadLink, value); - } + _excelTemplateDownloadLink = value; + ConfigurationHelper.UpdateAppSetting(ConfigurationConstants.ExcelTemplateDownloadLink, value); } + } - public string DefaultCulture + public string DefaultCulture + { + get => _defaultCulture; + set { - get => _defaultCulture; - set - { - _defaultCulture = value; - ConfigurationHelper.UpdateAppSetting(nameof(DefaultCulture), value); - } + _defaultCulture = value; + ConfigurationHelper.UpdateAppSetting(nameof(DefaultCulture), value); } - - public string[] SupportedCultures { get; set; } } + + public string[] SupportedCultures { get; set; } } diff --git a/test/DbTool.Test/NameConverterTest.cs b/test/DbTool.Test/NameConverterTest.cs index 97d6301..8ea1bc6 100644 --- a/test/DbTool.Test/NameConverterTest.cs +++ b/test/DbTool.Test/NameConverterTest.cs @@ -1,39 +1,41 @@ -using DbTool.Core; +// Copyright (c) Weihan Li. All rights reserved. +// Licensed under the MIT license. + +using DbTool.Core; using Xunit; -namespace DbTool.Test +namespace DbTool.Test; + +public class NameConverterTest { - public class NameConverterTest - { - private readonly IModelNameConverter _converter; + private readonly IModelNameConverter _converter; - public NameConverterTest() - { - _converter = new ModelNameConverter(); - } + public NameConverterTest() + { + _converter = new ModelNameConverter(); + } - [Theory] - [InlineData("tabNotice", "Notice")] - [InlineData("tab_Notice", "Notice")] - [InlineData("tblNotice", "Notice")] - [InlineData("tbl_Notice", "Notice")] - [InlineData("tab_notice", "Notice")] - [InlineData("tab-notice", "Notice")] - [InlineData("project", "Project")] - [InlineData("user-profile", "UserProfile")] - [InlineData("userProfile", "UserProfile")] - [InlineData("user_profile", "UserProfile")] - public void TableToModelTest(string tableName, string expectedModelName) - { - Assert.Equal(expectedModelName, _converter.ConvertTableToModel(tableName)); - } + [Theory] + [InlineData("tabNotice", "Notice")] + [InlineData("tab_Notice", "Notice")] + [InlineData("tblNotice", "Notice")] + [InlineData("tbl_Notice", "Notice")] + [InlineData("tab_notice", "Notice")] + [InlineData("tab-notice", "Notice")] + [InlineData("project", "Project")] + [InlineData("user-profile", "UserProfile")] + [InlineData("userProfile", "UserProfile")] + [InlineData("user_profile", "UserProfile")] + public void TableToModelTest(string tableName, string expectedModelName) + { + Assert.Equal(expectedModelName, _converter.ConvertTableToModel(tableName)); + } - [Theory] - [InlineData("NoticeModel", "Notice")] - [InlineData("NoticeEntity", "Notice")] - public void ModelToTableTest(string modelName, string expectedTableName) - { - Assert.Equal(expectedTableName, _converter.ConvertModelToTable(modelName)); - } + [Theory] + [InlineData("NoticeModel", "Notice")] + [InlineData("NoticeEntity", "Notice")] + public void ModelToTableTest(string modelName, string expectedTableName) + { + Assert.Equal(expectedTableName, _converter.ConvertModelToTable(modelName)); } }