From 83a4bb80399a780f694f48833f10e698c239d033 Mon Sep 17 00:00:00 2001 From: igeekfan Date: Fri, 20 May 2022 02:52:58 +0800 Subject: [PATCH 1/3] =?UTF-8?q?#694=20:sparkles:=20Exception=E4=BF=A1?= =?UTF-8?q?=E6=81=AF=20=E5=9B=BD=E9=99=85=E5=8C=96=20=E5=A4=9A=E8=AF=AD?= =?UTF-8?q?=E8=A8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FreeSql.DbContext/DbContext/DbContext.cs | 6 +- FreeSql.DbContext/DbSet/DbSet.cs | 30 +- FreeSql.DbContext/DbSet/DbSetAsync.cs | 16 +- FreeSql.DbContext/DbSet/DbSetSync.cs | 20 +- .../EfCoreFluentApi/EfCoreTableFluent.cs | 48 +- .../EfCoreFluentApi/EfCoreTableFluent`1.cs | 40 +- .../Extensions/DependencyInjection.cs | 4 +- FreeSql.DbContext/FreeSql.DbContext.csproj | 26 + FreeSql.DbContext/FreeSql.DbContext.xml | 230 ++++- .../Properties/DbContextStrings.Designer.cs | 357 +++++++ .../Properties/DbContextStrings.Designer.tt | 5 + .../Properties/DbContextStrings.en-US.resx | 246 +++++ .../Properties/DbContextStrings.resx | 246 +++++ .../Repository/ContextSet/RepositoryDbSet.cs | 4 +- .../Repository/DataFilter/DataFilterUtil.cs | 2 +- .../Repository/Repository/BaseRepository.cs | 8 +- FreeSql.DbContext/UnitOfWork/UnitOfWork.cs | 2 +- .../UnitOfWork/UnitOfWorkManager.cs | 8 +- .../Properties/CoreStringsTests.cs | 657 ++++++++++++ .../Properties/DbContextStringsTests.cs | 260 +++++ FreeSql.Tests/FreeSql.Tests/UnitTest5.cs | 5 + FreeSql.sln | 2 + FreeSql/DataAnnotations/TableAttribute.cs | 30 +- FreeSql/DataAnnotations/TableFluent.cs | 13 +- FreeSql/Extensions/AdoNetExtensions.cs | 28 +- .../FreeSqlGlobalExpressionCallExtensions.cs | 2 +- FreeSql/Extensions/FreeSqlGlobalExtensions.cs | 34 +- FreeSql/FreeSql.csproj | 30 + FreeSql/FreeSql.xml | 641 ++++++++++++ FreeSql/FreeSqlBuilder.cs | 16 +- FreeSql/Internal/CommonExpression.cs | 95 +- .../CommonProvider/AdoProvider/AdoProvider.cs | 3 +- .../AdoProvider/AdoProviderAsync.cs | 2 +- .../AdoProvider/AdoProviderTransaction.cs | 2 +- .../Internal/CommonProvider/BaseDbProvider.cs | 8 +- .../Internal/CommonProvider/DeleteProvider.cs | 4 +- .../CommonProvider/InsertOrUpdateProvider.cs | 18 +- .../Internal/CommonProvider/InsertProvider.cs | 24 +- .../CommonProvider/InsertProviderAsync.cs | 18 +- .../SelectProvider/Select0Provider.cs | 41 +- .../SelectProvider/Select0ProviderReader.cs | 20 +- .../SelectProvider/Select1Provider.cs | 49 +- .../SelectProvider/SelectGroupingProvider.cs | 2 +- .../Internal/CommonProvider/UpdateProvider.cs | 42 +- .../CommonProvider/UpdateProviderAsync.cs | 12 +- FreeSql/Internal/ObjectPool/ObjectPool.cs | 31 +- FreeSql/Internal/UtilsExpressionTree.cs | 61 +- FreeSql/Properties/CoreStrings.Designer.cs | 977 ++++++++++++++++++ FreeSql/Properties/CoreStrings.Designer.tt | 5 + FreeSql/Properties/CoreStrings.en-US.resx | 498 +++++++++ FreeSql/Properties/CoreStrings.resx | 498 +++++++++ FreeSql/Properties/Resources.tt | 261 +++++ .../ClickHouseExpression.cs | 2 +- .../Curd/DamengInsertOrUpdate.cs | 2 +- .../DamengExpression.cs | 2 +- .../Curd/FirebirdInsertOrUpdate.cs | 2 +- .../FirebirdExpression.cs | 2 +- .../Curd/GBaseInsertOrUpdate.cs | 2 +- .../FreeSql.Provider.GBase/GBaseExpression.cs | 2 +- .../KingbaseESExpression.cs | 2 +- .../MsAccessExpression.cs | 2 +- .../FreeSql.Provider.MySql/MySqlExpression.cs | 2 +- .../Dameng/Curd/OdbcDamengInsertOrUpdate.cs | 2 +- .../Dameng/OdbcDamengExpression.cs | 2 +- .../KingbaseES/OdbcKingbaseESExpression.cs | 2 +- .../MySql/OdbcMySqlExpression.cs | 2 +- .../Oracle/Curd/OdbcOracleInsertOrUpdate.cs | 2 +- .../Oracle/OdbcOracleExpression.cs | 2 +- .../PostgreSQL/OdbcPostgreSQLExpression.cs | 2 +- .../Curd/OdbcSqlServerInsertOrUpdate.cs | 2 +- .../SqlServer/OdbcSqlServerExpression.cs | 2 +- .../Curd/OracleInsertOrUpdate.cs | 2 +- .../OracleExpression.cs | 2 +- .../PostgreSQLExpression.cs | 2 +- .../Curd/ShenTongInsertOrUpdate.cs | 2 +- .../ShenTongExpression.cs | 2 +- .../Curd/SqlServerInsertOrUpdate.cs | 2 +- .../SqlServerExpression.cs | 2 +- .../SqliteExpression.cs | 2 +- 79 files changed, 5343 insertions(+), 398 deletions(-) create mode 100644 FreeSql.DbContext/Properties/DbContextStrings.Designer.cs create mode 100644 FreeSql.DbContext/Properties/DbContextStrings.Designer.tt create mode 100644 FreeSql.DbContext/Properties/DbContextStrings.en-US.resx create mode 100644 FreeSql.DbContext/Properties/DbContextStrings.resx create mode 100644 FreeSql.Tests/FreeSql.Tests/Properties/CoreStringsTests.cs create mode 100644 FreeSql.Tests/FreeSql.Tests/Properties/DbContextStringsTests.cs create mode 100644 FreeSql/Properties/CoreStrings.Designer.cs create mode 100644 FreeSql/Properties/CoreStrings.Designer.tt create mode 100644 FreeSql/Properties/CoreStrings.en-US.resx create mode 100644 FreeSql/Properties/CoreStrings.resx create mode 100644 FreeSql/Properties/Resources.tt diff --git a/FreeSql.DbContext/DbContext/DbContext.cs b/FreeSql.DbContext/DbContext/DbContext.cs index efcbcc5f6..e28fb1744 100644 --- a/FreeSql.DbContext/DbContext/DbContext.cs +++ b/FreeSql.DbContext/DbContext/DbContext.cs @@ -12,12 +12,12 @@ namespace FreeSql public abstract partial class DbContext : IDisposable { internal DbContextScopedFreeSql _ormScoped; - internal IFreeSql OrmOriginal => _ormScoped?._originalFsql ?? throw new ArgumentNullException("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql"); + internal IFreeSql OrmOriginal => _ormScoped?._originalFsql ?? throw new ArgumentNullException(DbContextStrings.ConfigureUseFreeSql); /// /// 该对象 Select/Delete/Insert/Update/InsertOrUpdate 与 DbContext 事务保持一致,可省略传递 WithTransaction /// - public IFreeSql Orm => _ormScoped ?? throw new ArgumentNullException("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql"); + public IFreeSql Orm => _ormScoped ?? throw new ArgumentNullException(DbContextStrings.ConfigureUseFreeSql); #region Property UnitOfWork internal bool _isUseUnitOfWork = true; //是否创建工作单元事务 @@ -126,7 +126,7 @@ public virtual IDbSet Set(Type entityType) void CheckEntityTypeOrThrow(Type entityType) { if (OrmOriginal.CodeFirst.GetTableByEntity(entityType) == null) - throw new ArgumentException($"参数 data 类型错误 {entityType.FullName} "); + throw new ArgumentException(DbContextStrings.ParameterDataTypeError(entityType.FullName)); } /// /// 添加 diff --git a/FreeSql.DbContext/DbSet/DbSet.cs b/FreeSql.DbContext/DbSet/DbSet.cs index 80d68252d..a1f5f891a 100644 --- a/FreeSql.DbContext/DbSet/DbSet.cs +++ b/FreeSql.DbContext/DbSet/DbSet.cs @@ -140,11 +140,11 @@ internal void TrackToList(object list) /// public DbSet AsType(Type entityType) { - if (entityType == typeof(object)) throw new Exception("ISelect.AsType 参数不支持指定为 object"); + if (entityType == typeof(object)) throw new Exception(CoreStrings.TypeAsType_NotSupport_Object("DbSet")); if (entityType == _entityType) return this; var newtb = _db.OrmOriginal.CodeFirst.GetTableByEntity(entityType); _entityType = entityType; - _tablePriv = newtb ?? throw new Exception("DbSet.AsType 参数错误,请传入正确的实体类型"); + _tablePriv = newtb ?? throw new Exception(CoreStrings.Type_AsType_Parameter_Error("DbSet")); _tableIdentitysPriv = null; _tableReturnColumnsPriv = null; return this; @@ -197,11 +197,11 @@ public EntityState(TEntity value, string key) public void AttachRange(IEnumerable data) { if (data == null || data.Any() == false) return; - if (_table.Primarys.Any() == false) throw new Exception($"不可附加,实体没有主键:{_db.OrmOriginal.GetEntityString(_entityType, data.First())}"); + if (_table.Primarys.Any() == false) throw new Exception(DbContextStrings.CannotAttach_EntityHasNo_PrimaryKey(_db.OrmOriginal.GetEntityString(_entityType, data.First()))); foreach (var item in data) { var key = _db.OrmOriginal.GetEntityKeyString(_entityType, item, false); - if (string.IsNullOrEmpty(key)) throw new Exception($"不可附加,未设置主键的值:{_db.OrmOriginal.GetEntityString(_entityType, item)}"); + if (string.IsNullOrEmpty(key)) throw new Exception(DbContextStrings.CannotAttach_PrimaryKey_NotSet(_db.OrmOriginal.GetEntityString(_entityType, item))); _states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) => { @@ -236,9 +236,9 @@ public DbSet AttachOnlyPrimary(TEntity data) public Dictionary CompareState(TEntity newdata) { if (newdata == null) return null; - if (_table.Primarys.Any() == false) throw new Exception($"不可比较,实体没有主键:{_db.OrmOriginal.GetEntityString(_entityType, newdata)}"); + if (_table.Primarys.Any() == false) throw new Exception(DbContextStrings.Incomparable_EntityHasNo_PrimaryKey(_db.OrmOriginal.GetEntityString(_entityType, newdata))); var key = _db.OrmOriginal.GetEntityKeyString(_entityType, newdata, false); - if (string.IsNullOrEmpty(key)) throw new Exception($"不可比较,未设置主键的值:{_db.OrmOriginal.GetEntityString(_entityType, newdata)}"); + if (string.IsNullOrEmpty(key)) throw new Exception(DbContextStrings.Incomparable_PrimaryKey_NotSet(_db.OrmOriginal.GetEntityString(_entityType, newdata))); if (_states.TryGetValue(key, out var oldState) == false || oldState == null) return _table.ColumnsByCs.ToDictionary(a => a.Key, a => new object[] { @@ -298,7 +298,7 @@ bool CanAdd(TEntity data, bool isThrow) } if (_table.Primarys.Any() == false) { - if (isThrow) throw new Exception($"不可添加,实体没有主键:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (isThrow) throw new Exception(DbContextStrings.CannotAdd_EntityHasNo_PrimaryKey(_db.OrmOriginal.GetEntityString(_entityType, data))); return false; } FreeSql.Internal.CommonProvider.InsertProvider.AuditDataValue(this, data, _db.OrmOriginal, _table, null); @@ -319,7 +319,7 @@ bool CanAdd(TEntity data, bool isThrow) default: if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) return true; - if (isThrow) throw new Exception($"不可添加,未设置主键的值:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (isThrow) throw new Exception(DbContextStrings.CannotAdd_PrimaryKey_NotSet(_db.OrmOriginal.GetEntityString(_entityType, data))); return false; } } @@ -327,14 +327,14 @@ bool CanAdd(TEntity data, bool isThrow) { if (_states.ContainsKey(key)) { - if (isThrow) throw new Exception($"不可添加,已存在于状态管理:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (isThrow) throw new Exception(DbContextStrings.CannotAdd_AlreadyExistsInStateManagement(_db.OrmOriginal.GetEntityString(_entityType, data))); return false; } if (_db.OrmOriginal.Ado.DataType == DataType.ClickHouse) return true; var idval = _db.OrmOriginal.GetEntityIdentityValueWithPrimary(_entityType, data); if (idval > 0) { - if (isThrow) throw new Exception($"不可添加,自增属性有值:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (isThrow) throw new Exception(DbContextStrings.CannotAdd_SelfIncreasingHasValue(_db.OrmOriginal.GetEntityString(_entityType, data))); return false; } } @@ -361,19 +361,19 @@ bool CanUpdate(TEntity data, bool isThrow) } if (_table.Primarys.Any() == false) { - if (isThrow) throw new Exception($"不可更新,实体没有主键:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (isThrow) throw new Exception(DbContextStrings.CannotUpdate_EntityHasNo_PrimaryKey(_db.OrmOriginal.GetEntityString(_entityType, data))); return false; } FreeSql.Internal.CommonProvider.UpdateProvider.AuditDataValue(this, data, _db.OrmOriginal, _table, null); var key = _db.OrmOriginal.GetEntityKeyString(_entityType, data, false); if (string.IsNullOrEmpty(key)) { - if (isThrow) throw new Exception($"不可更新,未设置主键的值:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (isThrow) throw new Exception(DbContextStrings.CannotUpdate_PrimaryKey_NotSet(_db.OrmOriginal.GetEntityString(_entityType, data))); return false; } if (_states.TryGetValue(key, out var tryval) == false) { - if (isThrow) throw new Exception($"不可更新,数据未被跟踪,应该先查询 或者 Attach:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (isThrow) throw new Exception(DbContextStrings.CannotUpdate_DataShouldQueryOrAttach(_db.OrmOriginal.GetEntityString(_entityType, data))); return false; } return true; @@ -399,13 +399,13 @@ bool CanRemove(TEntity data, bool isThrow) } if (_table.Primarys.Any() == false) { - if (isThrow) throw new Exception($"不可删除,实体没有主键:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (isThrow) throw new Exception(DbContextStrings.CannotDelete_EntityHasNo_PrimaryKey(_db.OrmOriginal.GetEntityString(_entityType, data))); return false; } var key = _db.OrmOriginal.GetEntityKeyString(_entityType, data, false); if (string.IsNullOrEmpty(key)) { - if (isThrow) throw new Exception($"不可删除,未设置主键的值:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (isThrow) throw new Exception(DbContextStrings.CannotDelete_PrimaryKey_NotSet(_db.OrmOriginal.GetEntityString(_entityType, data))); return false; } //if (_states.TryGetValue(key, out var tryval) == false) { diff --git a/FreeSql.DbContext/DbSet/DbSetAsync.cs b/FreeSql.DbContext/DbSet/DbSetAsync.cs index 6be0573cf..d822afc39 100644 --- a/FreeSql.DbContext/DbSet/DbSetAsync.cs +++ b/FreeSql.DbContext/DbSet/DbSetAsync.cs @@ -114,7 +114,7 @@ async public Task AddRangeAsync(IEnumerable data, CancellationToken can case DataType.ShenTong: await DbContextFlushCommandAsync(cancellationToken); var rets = await this.OrmInsert(data).ExecuteInsertedAsync(cancellationToken); - if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_db.OrmOriginal.Ado.DataType} 的返回数据,与添加的数目不匹配"); + if (rets.Count != data.Count()) throw new Exception(DbContextStrings.SpecialError_BatchAdditionFailed(_db.OrmOriginal.Ado.DataType)); _db._entityChangeReport.AddRange(rets.Select(a => new DbContext.EntityChangeReport.ChangeInfo { Object = a, Type = DbContext.EntityChangeType.Insert })); var idx = 0; foreach (var s in data) @@ -148,8 +148,8 @@ async public Task SaveManyAsync(TEntity item, string propertyName, CancellationT { if (item == null) return; if (string.IsNullOrEmpty(propertyName)) return; - if (_table.Properties.TryGetValue(propertyName, out var prop) == false) throw new KeyNotFoundException($"{_table.Type.FullName} 不存在属性 {propertyName}"); - if (_table.ColumnsByCsIgnore.ContainsKey(propertyName)) throw new ArgumentException($"{_table.Type.FullName} 类型已设置属性 {propertyName} 忽略特性"); + if (_table.Properties.TryGetValue(propertyName, out var prop) == false) throw new KeyNotFoundException(DbContextStrings.NotFound_Property(_table.Type.FullName, propertyName)); + if (_table.ColumnsByCsIgnore.ContainsKey(propertyName)) throw new ArgumentException(DbContextStrings.TypeHasSetProperty_IgnoreAttribute(_table.Type.FullName, propertyName)); var tref = _table.GetTableRef(propertyName, true); if (tref == null) return; @@ -157,7 +157,7 @@ async public Task SaveManyAsync(TEntity item, string propertyName, CancellationT { case Internal.Model.TableRefType.OneToOne: case Internal.Model.TableRefType.ManyToOne: - throw new ArgumentException($"{_table.Type.FullName} 类型的属性 {propertyName} 不是 OneToMany 或 ManyToMany 特性"); + throw new ArgumentException(DbContextStrings.PropertyOfType_IsNot_OneToManyOrManyToMany(_table.Type.FullName, propertyName)); } await DbContextFlushCommandAsync(cancellationToken); @@ -363,7 +363,7 @@ async Task DbContextBatchUpdatePrivAsync(EntityState[] ups, bool isLiveUpda if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999; var lstval2 = default(EntityState); - if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_db.OrmOriginal.GetEntityString(_entityType, uplst2.Value)}"); + if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception(DbContextStrings.SpecialError_UpdateFailedDataNotTracked(_db.OrmOriginal.GetEntityString(_entityType, uplst2.Value))); var cuig1 = _db.OrmOriginal.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true); var cuig2 = uplst2 != null ? _db.OrmOriginal.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null; @@ -413,11 +413,11 @@ async Task DbContextBatchUpdatePrivAsync(EntityState[] ups, bool isLiveUpda async public Task UpdateAsync(TEntity data, CancellationToken cancellationToken = default) { var exists = ExistsInStates(data); - if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (exists == null) throw new Exception(DbContextStrings.CannotUpdate_PrimaryKey_NotSet(_db.OrmOriginal.GetEntityString(_entityType, data))); if (exists == false) { var olddata = await OrmSelect(data).FirstAsync(cancellationToken); - if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (olddata == null) throw new Exception(DbContextStrings.CannotUpdate_RecordDoesNotExist(_db.OrmOriginal.GetEntityString(_entityType, data))); } await UpdateRangePrivAsync(new[] { data }, true, cancellationToken); @@ -472,7 +472,7 @@ async public Task RemoveAsync(Expression> predicate, Ca async public Task AddOrUpdateAsync(TEntity data, CancellationToken cancellationToken = default) { if (data == null) throw new ArgumentNullException(nameof(data)); - if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (_table.Primarys.Any() == false) throw new Exception(DbContextStrings.CannotAdd_EntityHasNo_PrimaryKey(_db.OrmOriginal.GetEntityString(_entityType, data))); var flagExists = ExistsInStates(data); if (flagExists == false) diff --git a/FreeSql.DbContext/DbSet/DbSetSync.cs b/FreeSql.DbContext/DbSet/DbSetSync.cs index 740746e08..d295033cd 100644 --- a/FreeSql.DbContext/DbSet/DbSetSync.cs +++ b/FreeSql.DbContext/DbSet/DbSetSync.cs @@ -116,7 +116,7 @@ public void AddRange(IEnumerable data) case DataType.ShenTong: DbContextFlushCommand(); var rets = this.OrmInsert(data).ExecuteInserted(); - if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_db.OrmOriginal.Ado.DataType} 的返回数据,与添加的数目不匹配"); + if (rets.Count != data.Count()) throw new Exception(DbContextStrings.SpecialError_BatchAdditionFailed(_db.OrmOriginal.Ado.DataType)); _db._entityChangeReport.AddRange(rets.Select(a => new DbContext.EntityChangeReport.ChangeInfo { Object = a, Type = DbContext.EntityChangeType.Insert })); var idx = 0; foreach (var s in data) @@ -159,8 +159,8 @@ public void SaveMany(TEntity item, string propertyName) { if (item == null) return; if (string.IsNullOrEmpty(propertyName)) return; - if (_table.Properties.TryGetValue(propertyName, out var prop) == false) throw new KeyNotFoundException($"{_table.Type.FullName} 不存在属性 {propertyName}"); - if (_table.ColumnsByCsIgnore.ContainsKey(propertyName)) throw new ArgumentException($"{_table.Type.FullName} 类型已设置属性 {propertyName} 忽略特性"); + if (_table.Properties.TryGetValue(propertyName, out var prop) == false) throw new KeyNotFoundException(DbContextStrings.NotFound_Property(_table.Type.FullName, propertyName)); + if (_table.ColumnsByCsIgnore.ContainsKey(propertyName)) throw new ArgumentException(DbContextStrings.TypeHasSetProperty_IgnoreAttribute(_table.Type.FullName, propertyName)); var tref = _table.GetTableRef(propertyName, true); if (tref == null) return; @@ -168,7 +168,7 @@ public void SaveMany(TEntity item, string propertyName) { case Internal.Model.TableRefType.OneToOne: case Internal.Model.TableRefType.ManyToOne: - throw new ArgumentException($"{_table.Type.FullName} 类型的属性 {propertyName} 不是 OneToMany 或 ManyToMany 特性"); + throw new ArgumentException(DbContextStrings.PropertyOfType_IsNot_OneToManyOrManyToMany(_table.Type.FullName, propertyName)); } DbContextFlushCommand(); @@ -397,7 +397,7 @@ int DbContextBatchUpdatePriv(EntityState[] ups, bool isLiveUpdate) if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999; var lstval2 = default(EntityState); - if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_db.OrmOriginal.GetEntityString(_entityType, uplst2.Value)}"); + if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception(DbContextStrings.SpecialError_UpdateFailedDataNotTracked(_db.OrmOriginal.GetEntityString(_entityType, uplst2.Value))); var cuig1 = _db.OrmOriginal.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true); var cuig2 = uplst2 != null ? _db.OrmOriginal.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null; @@ -454,11 +454,11 @@ int DbContextBatchUpdatePriv(EntityState[] ups, bool isLiveUpdate) public void Update(TEntity data) { var exists = ExistsInStates(data); - if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (exists == null) throw new Exception(DbContextStrings.CannotUpdate_PrimaryKey_NotSet(_db.OrmOriginal.GetEntityString(_entityType, data))); if (exists == false) { var olddata = OrmSelect(data).First(); - if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (olddata == null) throw new Exception(DbContextStrings.CannotUpdate_RecordDoesNotExist(_db.OrmOriginal.GetEntityString(_entityType, data))); } UpdateRangePriv(new[] { data }, true); @@ -545,7 +545,7 @@ public int Remove(Expression> predicate) public void AddOrUpdate(TEntity data) { if (data == null) throw new ArgumentNullException(nameof(data)); - if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_db.OrmOriginal.GetEntityString(_entityType, data)}"); + if (_table.Primarys.Any() == false) throw new Exception(DbContextStrings.CannotAdd_EntityHasNo_PrimaryKey(_db.OrmOriginal.GetEntityString(_entityType, data))); var flagExists = ExistsInStates(data); if (flagExists == false) @@ -585,7 +585,7 @@ public void AddOrUpdate(TEntity data) public void BeginEdit(List data) { if (data == null) return; - if (_table.Primarys.Any() == false) throw new Exception($"不可进行编辑,实体没有主键:{_db.OrmOriginal.GetEntityString(_entityType, data.First())}"); + if (_table.Primarys.Any() == false) throw new Exception(DbContextStrings.CannotEdit_EntityHasNo_PrimaryKey(_db.OrmOriginal.GetEntityString(_entityType, data.First()))); _statesEditing.Clear(); _dataEditing = data; foreach (var item in data) @@ -875,7 +875,7 @@ void LocalEach(DbSet dbset, IEnumerable items, bool isOneToOne) var rawset = _db.Set(dbset.EntityType); var statesRemove = typeof(DbSet<>).MakeGenericType(dbset.EntityType).GetMethod("StatesRemoveByObjects", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(IEnumerable) }, null); - if (statesRemove == null) throw new Exception("找不到方法 DbSet<>.StatesRemoveByObjects"); + if (statesRemove == null) throw new Exception(DbContextStrings.NotFoundMethod_StatesRemoveByObjects); statesRemove.Invoke(rawset, new object[] { items }); } returnDeleted?.AddRange(items); diff --git a/FreeSql.DbContext/EfCoreFluentApi/EfCoreTableFluent.cs b/FreeSql.DbContext/EfCoreFluentApi/EfCoreTableFluent.cs index bed4b4c07..27ffbe880 100644 --- a/FreeSql.DbContext/EfCoreFluentApi/EfCoreTableFluent.cs +++ b/FreeSql.DbContext/EfCoreFluentApi/EfCoreTableFluent.cs @@ -42,7 +42,7 @@ public EfCoreTableFluent ToView(string name) #region HasKey public EfCoreTableFluent HasKey(string key) { - if (key == null) throw new ArgumentException("参数错误 key 不能为 null"); + if (key == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("key")); foreach (string name in key.Split(',')) { if (string.IsNullOrEmpty(name.Trim())) continue; @@ -55,7 +55,7 @@ public EfCoreTableFluent HasKey(string key) #region HasIndex public HasIndexFluent HasIndex(string index) { - if (index == null) throw new ArgumentException("参数错误 index 不能为 null"); + if (index == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("index")); var indexName = $"idx_{Guid.NewGuid().ToString("N").Substring(0, 8)}"; var columns = new List(); foreach (string name in index.Split(',')) @@ -98,8 +98,8 @@ public HasIndexFluent HasName(string name) #region HasOne public HasOneFluent HasOne(string one) { - if (string.IsNullOrEmpty(one)) throw new ArgumentException("参数错误 one 不能为 null"); - if (_entityType.GetPropertiesDictIgnoreCase().TryGetValue(one, out var oneProperty) == false) throw new ArgumentException($"参数错误 {one} 属性不存在"); + if (string.IsNullOrEmpty(one)) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("one")); + if (_entityType.GetPropertiesDictIgnoreCase().TryGetValue(one, out var oneProperty) == false) throw new ArgumentException(DbContextStrings.ParameterError_NotFound_Property(one)); return new HasOneFluent(_fsql, _tf, _entityType, oneProperty.PropertyType, one); } public class HasOneFluent @@ -124,8 +124,8 @@ internal HasOneFluent(IFreeSql fsql, TableFluent modelBuilder, Type entityType1, } public HasOneFluent WithMany(string many) { - if (many == null) throw new ArgumentException("参数错误 many 不能为 null"); - if (_entityType2.GetPropertiesDictIgnoreCase().TryGetValue(many, out var manyProperty) == false) throw new ArgumentException($"参数错误 {many} 属性不存在"); + if (many == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("many")); + if (_entityType2.GetPropertiesDictIgnoreCase().TryGetValue(many, out var manyProperty) == false) throw new ArgumentException(DbContextStrings.ParameterError_NotFound_Property(many)); _withManyProperty = manyProperty.Name; if (string.IsNullOrEmpty(_selfBind) == false) _fsql.CodeFirst.ConfigEntity(_entityType2, eb2 => eb2.Navigate(many, _selfBind)); @@ -133,18 +133,18 @@ public HasOneFluent WithMany(string many) } public HasOneFluent WithOne(string one, string foreignKey) { - if (string.IsNullOrEmpty(one)) throw new ArgumentException("参数错误 one 不能为 null"); - if (_entityType1.GetPropertiesDictIgnoreCase().TryGetValue(one, out var oneProperty) == false) throw new ArgumentException($"参数错误 {one} 属性不存在"); - if (oneProperty != _entityType1) throw new ArgumentException($"参数错误 {one} 属性不存在"); + if (string.IsNullOrEmpty(one)) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("one")); + if (_entityType1.GetPropertiesDictIgnoreCase().TryGetValue(one, out var oneProperty) == false) throw new ArgumentException(DbContextStrings.ParameterError_NotFound_Property(one)); + if (oneProperty != _entityType1) throw new ArgumentException(DbContextStrings.ParameterError_NotFound_Property(one)); _withOneProperty = oneProperty.Name; - if (foreignKey == null) throw new ArgumentException("参数错误 foreignKey 不能为 null"); + if (foreignKey == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("foreignKey")); foreach (string name in foreignKey.Split(',')) { if (string.IsNullOrEmpty(name.Trim())) continue; _withOneBind += ", " + name.Trim(); } - if (string.IsNullOrEmpty(_withOneBind)) throw new ArgumentException("参数错误 foreignKey"); + if (string.IsNullOrEmpty(_withOneBind)) throw new ArgumentException(DbContextStrings.ParameterError("foreignKey")); _withOneBind = _withOneBind.TrimStart(',', ' '); if (string.IsNullOrEmpty(_selfBind) == false) _fsql.CodeFirst.ConfigEntity(_entityType2, eb2 => eb2.Navigate(_withOneProperty, _withOneBind)); @@ -152,13 +152,13 @@ public HasOneFluent WithOne(string one, string foreignKey) } public HasOneFluent HasForeignKey(string foreignKey) { - if (foreignKey == null) throw new ArgumentException("参数错误 foreignKey 不能为 null"); + if (foreignKey == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("foreignKey")); foreach (string name in foreignKey.Split(',')) { if (string.IsNullOrEmpty(name.Trim())) continue; _selfBind += ", " + name.Trim(); } - if (string.IsNullOrEmpty(_selfBind)) throw new ArgumentException("参数错误 foreignKey"); + if (string.IsNullOrEmpty(_selfBind)) throw new ArgumentException(DbContextStrings.ParameterError("foreignKey")); _selfBind = _selfBind.TrimStart(',', ' '); _tf.Navigate(_selfProperty, _selfBind); if (string.IsNullOrEmpty(_withManyProperty) == false) @@ -173,9 +173,9 @@ public HasOneFluent HasForeignKey(string foreignKey) #region HasMany public HasManyFluent HasMany(string many) { - if (string.IsNullOrEmpty(many)) throw new ArgumentException("参数错误 many 不能为 null"); - if (_entityType.GetPropertiesDictIgnoreCase().TryGetValue(many, out var manyProperty) == false) throw new ArgumentException($"参数错误 {many} 集合属性不存在"); - if (typeof(IEnumerable).IsAssignableFrom(manyProperty.PropertyType) == false || manyProperty.PropertyType.IsGenericType == false) throw new ArgumentException("参数错误 {many} 不是集合属性"); + if (string.IsNullOrEmpty(many)) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("many")); + if (_entityType.GetPropertiesDictIgnoreCase().TryGetValue(many, out var manyProperty) == false) throw new ArgumentException(DbContextStrings.ParameterError_NotFound_CollectionProperties(many)); + if (typeof(IEnumerable).IsAssignableFrom(manyProperty.PropertyType) == false || manyProperty.PropertyType.IsGenericType == false) throw new ArgumentException(DbContextStrings.ParameterError_IsNot_CollectionProperties(many)); return new HasManyFluent(_fsql, _tf, _entityType, manyProperty.PropertyType.GetGenericArguments()[0], manyProperty.Name); } public class HasManyFluent @@ -200,18 +200,18 @@ internal HasManyFluent(IFreeSql fsql, TableFluent modelBuilder, Type entityType1 public void WithMany(string many, Type middleType) { - if (string.IsNullOrEmpty(many)) throw new ArgumentException("参数错误 many 不能为 null"); - if (_entityType2.GetPropertiesDictIgnoreCase().TryGetValue(many, out var manyProperty) == false) throw new ArgumentException($"参数错误 {many} 集合属性不存在"); - if (typeof(IEnumerable).IsAssignableFrom(manyProperty.PropertyType) == false || manyProperty.PropertyType.IsGenericType == false) throw new ArgumentException("参数错误 {many} 不是集合属性"); + if (string.IsNullOrEmpty(many)) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("many")); + if (_entityType2.GetPropertiesDictIgnoreCase().TryGetValue(many, out var manyProperty) == false) throw new ArgumentException(DbContextStrings.ParameterError_NotFound_CollectionProperties(many)); + if (typeof(IEnumerable).IsAssignableFrom(manyProperty.PropertyType) == false || manyProperty.PropertyType.IsGenericType == false) throw new ArgumentException(DbContextStrings.ParameterError_IsNot_CollectionProperties(many)); _withManyProperty = manyProperty.Name; _tf.Navigate(_selfProperty, null, middleType); _fsql.CodeFirst.ConfigEntity(_entityType2, eb2 => eb2.Navigate(_withManyProperty, null, middleType)); } public HasManyFluent WithOne(string one) { - if (string.IsNullOrEmpty(one)) throw new ArgumentException("参数错误 one 不能为 null"); - if (_entityType2.GetPropertiesDictIgnoreCase().TryGetValue(one, out var oneProperty) == false) throw new ArgumentException($"参数错误 {one} 属性不存在"); - if (oneProperty.PropertyType != _entityType1) throw new ArgumentException($"参数错误 {one} 属性不存在"); + if (string.IsNullOrEmpty(one)) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("one")); + if (_entityType2.GetPropertiesDictIgnoreCase().TryGetValue(one, out var oneProperty) == false) throw new ArgumentException(DbContextStrings.ParameterError_NotFound_Property(one)); + if (oneProperty.PropertyType != _entityType1) throw new ArgumentException(DbContextStrings.ParameterError_NotFound_Property(one)); _withOneProperty = oneProperty.Name; if (string.IsNullOrEmpty(_selfBind) == false) _fsql.CodeFirst.ConfigEntity(_entityType2, eb2 => eb2.Navigate(oneProperty.Name, _selfBind)); @@ -219,13 +219,13 @@ public HasManyFluent WithOne(string one) } public HasManyFluent HasForeignKey(string foreignKey) { - if (foreignKey == null) throw new ArgumentException("参数错误 foreignKey 不能为 null"); + if (foreignKey == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("foreignKey")); foreach (string name in foreignKey.Split(',')) { if (string.IsNullOrEmpty(name.Trim())) continue; _selfBind += ", " + name.Trim(); } - if (string.IsNullOrEmpty(_selfBind)) throw new ArgumentException("参数错误 foreignKey"); + if (string.IsNullOrEmpty(_selfBind)) throw new ArgumentException(DbContextStrings.ParameterError("foreignKey")); _selfBind = _selfBind.TrimStart(',', ' '); _tf.Navigate(_selfProperty, _selfBind); if (string.IsNullOrEmpty(_withOneProperty) == false) diff --git a/FreeSql.DbContext/EfCoreFluentApi/EfCoreTableFluent`1.cs b/FreeSql.DbContext/EfCoreFluentApi/EfCoreTableFluent`1.cs index 3cd561ad3..e142bd75a 100644 --- a/FreeSql.DbContext/EfCoreFluentApi/EfCoreTableFluent`1.cs +++ b/FreeSql.DbContext/EfCoreFluentApi/EfCoreTableFluent`1.cs @@ -42,7 +42,7 @@ public EfCoreTableFluent HasKey(Expression> key) { var exp = key?.Body; if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand; - if (exp == null) throw new ArgumentException("参数错误 key 不能为 null"); + if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("key")); switch (exp.NodeType) { @@ -63,7 +63,7 @@ public HasIndexFluent HasIndex(Expression> index) { var exp = index?.Body; if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand; - if (exp == null) throw new ArgumentException("参数错误 index 不能为 null"); + if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("index")); var indexName = $"idx_{Guid.NewGuid().ToString("N").Substring(0, 8)}"; var columns = new List(); @@ -114,7 +114,7 @@ public HasOneFluent HasOne(Expression> one) { var exp = one?.Body; if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand; - if (exp == null) throw new ArgumentException("参数错误 one 不能为 null"); + if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("one")); var oneProperty = ""; switch (exp.NodeType) @@ -123,7 +123,7 @@ public HasOneFluent HasOne(Expression> one) oneProperty = (exp as MemberExpression).Member.Name; break; } - if (string.IsNullOrEmpty(oneProperty)) throw new ArgumentException("参数错误 one"); + if (string.IsNullOrEmpty(oneProperty)) throw new ArgumentException(DbContextStrings.ParameterError("one")); return new HasOneFluent(_fsql, _tf, oneProperty); } public class HasOneFluent @@ -146,7 +146,7 @@ public HasOneFluent WithMany(Expression> many) { var exp = many?.Body; if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand; - if (exp == null) throw new ArgumentException("参数错误 many 不能为 null"); + if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("many")); switch (exp.NodeType) { @@ -154,7 +154,7 @@ public HasOneFluent WithMany(Expression> many) _withManyProperty = (exp as MemberExpression).Member.Name; break; } - if (string.IsNullOrEmpty(_withManyProperty)) throw new ArgumentException("参数错误 many"); + if (string.IsNullOrEmpty(_withManyProperty)) throw new ArgumentException(DbContextStrings.ParameterError("many")); if (string.IsNullOrEmpty(_selfBind) == false) _fsql.CodeFirst.ConfigEntity(eb2 => eb2.Navigate(_withManyProperty, _selfBind)); return this; @@ -163,7 +163,7 @@ public HasOneFluent WithOne(Expression> one, Expression WithOne(Expression> one, Expression WithOne(Expression> one, Expression(eb2 => eb2.Navigate(_withOneProperty, _withOneBind)); return this; @@ -199,7 +199,7 @@ public HasOneFluent HasForeignKey(Expression> foreignKey) { var exp = foreignKey?.Body; if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand; - if (exp == null) throw new ArgumentException("参数错误 foreignKey 不能为 null"); + if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("foreignKey")); switch (exp.NodeType) { @@ -214,7 +214,7 @@ public HasOneFluent HasForeignKey(Expression> foreignKey) _selfBind = _selfBind.TrimStart(',', ' '); break; } - if (string.IsNullOrEmpty(_selfBind)) throw new ArgumentException("参数错误 foreignKey"); + if (string.IsNullOrEmpty(_selfBind)) throw new ArgumentException(DbContextStrings.ParameterError("foreignKey")); _tf.Navigate(_selfProperty, _selfBind); if (string.IsNullOrEmpty(_withManyProperty) == false) _fsql.CodeFirst.ConfigEntity(eb2 => eb2.Navigate(_withManyProperty, _selfBind)); @@ -230,7 +230,7 @@ public HasManyFluent HasMany(Expression>> many) { var exp = many?.Body; if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand; - if (exp == null) throw new ArgumentException("参数错误 many 不能为 null"); + if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("many")); var manyProperty = ""; switch (exp.NodeType) @@ -239,7 +239,7 @@ public HasManyFluent HasMany(Expression>> many) manyProperty = (exp as MemberExpression).Member.Name; break; } - if (string.IsNullOrEmpty(manyProperty)) throw new ArgumentException("参数错误 many"); + if (string.IsNullOrEmpty(manyProperty)) throw new ArgumentException(DbContextStrings.ParameterError("many")); return new HasManyFluent(_fsql, _tf, manyProperty); } public class HasManyFluent @@ -262,7 +262,7 @@ public void WithMany(Expression>> many, Type middleType) { var exp = many?.Body; if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand; - if (exp == null) throw new ArgumentException("参数错误 many 不能为 null"); + if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("many")); switch (exp.NodeType) { @@ -270,7 +270,7 @@ public void WithMany(Expression>> many, Type middleType) _withManyProperty = (exp as MemberExpression).Member.Name; break; } - if (string.IsNullOrEmpty(_withManyProperty)) throw new ArgumentException("参数错误 many"); + if (string.IsNullOrEmpty(_withManyProperty)) throw new ArgumentException(DbContextStrings.ParameterError("many")); _tf.Navigate(_selfProperty, null, middleType); _fsql.CodeFirst.ConfigEntity(eb2 => eb2.Navigate(_withManyProperty, null, middleType)); @@ -279,7 +279,7 @@ public HasManyFluent WithOne(Expression> one) { var exp = one?.Body; if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand; - if (exp == null) throw new ArgumentException("参数错误 one 不能为 null"); + if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("one")); switch (exp.NodeType) { @@ -287,7 +287,7 @@ public HasManyFluent WithOne(Expression> one) _withOneProperty = (exp as MemberExpression).Member.Name; break; } - if (string.IsNullOrEmpty(_withOneProperty)) throw new ArgumentException("参数错误 one"); + if (string.IsNullOrEmpty(_withOneProperty)) throw new ArgumentException(DbContextStrings.ParameterError("one")); if (string.IsNullOrEmpty(_selfBind) == false) _fsql.CodeFirst.ConfigEntity(eb2 => eb2.Navigate(_withOneProperty, _selfBind)); @@ -297,7 +297,7 @@ public HasManyFluent HasForeignKey(Expression> foreignKey) { var exp = foreignKey?.Body; if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand; - if (exp == null) throw new ArgumentException("参数错误 foreignKey 不能为 null"); + if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("foreignKey")); switch (exp.NodeType) { @@ -312,7 +312,7 @@ public HasManyFluent HasForeignKey(Expression> foreignKey) _selfBind = _selfBind.TrimStart(',', ' '); break; } - if (string.IsNullOrEmpty(_selfBind)) throw new ArgumentException("参数错误 foreignKey"); + if (string.IsNullOrEmpty(_selfBind)) throw new ArgumentException(DbContextStrings.ParameterError("foreignKey")); _tf.Navigate(_selfProperty, _selfBind); if (string.IsNullOrEmpty(_withOneProperty) == false) _fsql.CodeFirst.ConfigEntity(eb2 => eb2.Navigate(_withOneProperty, _selfBind)); diff --git a/FreeSql.DbContext/Extensions/DependencyInjection.cs b/FreeSql.DbContext/Extensions/DependencyInjection.cs index dd96b306d..78664f09f 100644 --- a/FreeSql.DbContext/Extensions/DependencyInjection.cs +++ b/FreeSql.DbContext/Extensions/DependencyInjection.cs @@ -21,7 +21,7 @@ static IServiceCollection AddFreeDbContext(this IServiceCollection services, Typ } catch(Exception ex) { - throw new Exception($"AddFreeDbContext 发生错误,请检查 {dbContextType.Name} 的构造参数都已正确注入", ex); + throw new Exception(DbContextStrings.AddFreeDbContextError_CheckConstruction(dbContextType.Name), ex); } if (ctx != null && ctx._ormScoped == null) { @@ -31,7 +31,7 @@ static IServiceCollection AddFreeDbContext(this IServiceCollection services, Typ ctx._optionsPriv = builder._options; if (ctx._ormScoped == null) - throw new Exception("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql"); + throw new Exception(DbContextStrings.ConfigureUseFreeSql); ctx.InitPropSets(); } diff --git a/FreeSql.DbContext/FreeSql.DbContext.csproj b/FreeSql.DbContext/FreeSql.DbContext.csproj index ba3a98ceb..c6e643118 100644 --- a/FreeSql.DbContext/FreeSql.DbContext.csproj +++ b/FreeSql.DbContext/FreeSql.DbContext.csproj @@ -54,4 +54,30 @@ + + + + + + + True + True + DbContextStrings.Designer.tt + + + + + + TextTemplatingFileGenerator + DbContextStrings.Designer.cs + + + Designer + FreeSql + + + FreeSql + + + diff --git a/FreeSql.DbContext/FreeSql.DbContext.xml b/FreeSql.DbContext/FreeSql.DbContext.xml index eb0d0e63c..20d62ad18 100644 --- a/FreeSql.DbContext/FreeSql.DbContext.xml +++ b/FreeSql.DbContext/FreeSql.DbContext.xml @@ -255,6 +255,227 @@ + + + + String resources used in FreeSql exceptions, etc. + + + These strings are exposed publicly for use by database providers and extensions. + It is unusual for application code to need these strings. + + + + + + AddFreeDbContext 发生错误,请检查 {dbContextTypeName} 的构造参数都已正确注入 + + + + + 不可添加,已存在于状态管理:{entityString} + + + + + 不可添加,实体没有主键:{entityString} + + + + + 不可添加,未设置主键的值:{entityString} + + + + + 不可添加,自增属性有值:{entityString} + + + + + 不可附加,实体没有主键:{entityString} + + + + + 不可附加,未设置主键的值:{entityString} + + + + + 不可删除,数据未被跟踪,应该先查询:{entityString} + + + + + 不可删除,实体没有主键:{entityString} + + + + + 不可删除,未设置主键的值:{entityString} + + + + + 不可进行编辑,实体没有主键:{entityString} + + + + + 不可更新,数据未被跟踪,应该先查询 或者 Attach:{entityString} + + + + + 不可更新,实体没有主键:{entityString} + + + + + 不可更新,未设置主键的值:{entityString} + + + + + 不可更新,数据库不存在该记录:{entityString} + + + + + 请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql + + + + + DbSet.AsType 参数错误,请传入正确的实体类型 + + + + + 实体类型 {EntityTypeName} 无法转换为 {name},无法使用该方法 + + + + + 实体类型 {EntityTypeName} 主键类型不为 {fullName},无法使用该方法 + + + + + 实体类型 {EntityTypeName} 主键数量不为 1,无法使用该方法 + + + + + FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository + + + + + 不可比较,实体没有主键:{entityString} + + + + + 不可比较,未设置主键的值:{entityString} + + + + + FreeSql.Repository Insert 失败,因为设置了过滤器 {filterKey}: {filterValueExpression},插入的数据不符合 {entityString} + + + + + ISelect.AsType 参数不支持指定为 object + + + + + {tableTypeFullName} 不存在属性 {propertyName} + + + + + 找不到方法 DbSet<>.StatesRemoveByObjects + + + + + 参数 data 类型错误 {entityTypeFullName} + + + + + 参数错误 {param} + + + + + 参数错误 {param} 不能为 null + + + + + 参数错误 {many} 不是集合属性 + + + + + 参数错误 {many} 集合属性不存在 + + + + + 参数错误 {one} 属性不存在 + + + + + Propagation_Mandatory: 使用当前事务,如果没有当前事务,就抛出异常 + + + + + Propagation_Never: 以非事务方式执行操作,如果当前事务存在则抛出异常 + + + + + {tableTypeFullName} 类型的属性 {propertyName} 不是 OneToMany 或 ManyToMany 特性 + + + + + 特别错误:批量添加失败,{dataType} 的返回数据,与添加的数目不匹配 + + + + + 特别错误:更新失败,数据未被跟踪:{entityString} + + + + + 已开启事务,不能禁用工作单元 + + + + + {tableTypeFullName} 类型已设置属性 {propertyName} 忽略特性 + + + + + {unitOfWorkManager} 构造参数 {fsql} 不能为 null + + + + + FreeSql.Repository Update 失败,因为设置了过滤器 {filterKey}: {filterValueExpression},更新的数据不符合{entityString} + + 在工作单元内创建默认仓库类,工作单元下的仓储操作具有事务特点 @@ -559,14 +780,5 @@ - - - 批量注入 Repository,可以参考代码自行调整 - - - - - - diff --git a/FreeSql.DbContext/Properties/DbContextStrings.Designer.cs b/FreeSql.DbContext/Properties/DbContextStrings.Designer.cs new file mode 100644 index 000000000..44a9fd7d1 --- /dev/null +++ b/FreeSql.DbContext/Properties/DbContextStrings.Designer.cs @@ -0,0 +1,357 @@ + +// + +using System; +using System.Reflection; +using System.Resources; +using System.Threading; + +namespace FreeSql +{ + /// + /// + /// String resources used in FreeSql exceptions, etc. + /// + /// + /// These strings are exposed publicly for use by database providers and extensions. + /// It is unusual for application code to need these strings. + /// + /// + public static class DbContextStrings + { + private static readonly ResourceManager _resourceManager + = new ResourceManager("FreeSql.DbContext.Properties.DbContextStrings", typeof(DbContextStrings).Assembly); + + /// + /// AddFreeDbContext 发生错误,请检查 {dbContextTypeName} 的构造参数都已正确注入 + /// + public static string AddFreeDbContextError_CheckConstruction(object dbContextTypeName) + => string.Format( + GetString("AddFreeDbContextError_CheckConstruction", nameof(dbContextTypeName)), + dbContextTypeName); + + /// + /// 不可添加,已存在于状态管理:{entityString} + /// + public static string CannotAdd_AlreadyExistsInStateManagement(object entityString) + => string.Format( + GetString("CannotAdd_AlreadyExistsInStateManagement", nameof(entityString)), + entityString); + + /// + /// 不可添加,实体没有主键:{entityString} + /// + public static string CannotAdd_EntityHasNo_PrimaryKey(object entityString) + => string.Format( + GetString("CannotAdd_EntityHasNo_PrimaryKey", nameof(entityString)), + entityString); + + /// + /// 不可添加,未设置主键的值:{entityString} + /// + public static string CannotAdd_PrimaryKey_NotSet(object entityString) + => string.Format( + GetString("CannotAdd_PrimaryKey_NotSet", nameof(entityString)), + entityString); + + /// + /// 不可添加,自增属性有值:{entityString} + /// + public static string CannotAdd_SelfIncreasingHasValue(object entityString) + => string.Format( + GetString("CannotAdd_SelfIncreasingHasValue", nameof(entityString)), + entityString); + + /// + /// 不可附加,实体没有主键:{entityString} + /// + public static string CannotAttach_EntityHasNo_PrimaryKey(object entityString) + => string.Format( + GetString("CannotAttach_EntityHasNo_PrimaryKey", nameof(entityString)), + entityString); + + /// + /// 不可附加,未设置主键的值:{entityString} + /// + public static string CannotAttach_PrimaryKey_NotSet(object entityString) + => string.Format( + GetString("CannotAttach_PrimaryKey_NotSet", nameof(entityString)), + entityString); + + /// + /// 不可删除,数据未被跟踪,应该先查询:{entityString} + /// + public static string CannotDelete_DataNotTracked_ShouldQuery(object entityString) + => string.Format( + GetString("CannotDelete_DataNotTracked_ShouldQuery", nameof(entityString)), + entityString); + + /// + /// 不可删除,实体没有主键:{entityString} + /// + public static string CannotDelete_EntityHasNo_PrimaryKey(object entityString) + => string.Format( + GetString("CannotDelete_EntityHasNo_PrimaryKey", nameof(entityString)), + entityString); + + /// + /// 不可删除,未设置主键的值:{entityString} + /// + public static string CannotDelete_PrimaryKey_NotSet(object entityString) + => string.Format( + GetString("CannotDelete_PrimaryKey_NotSet", nameof(entityString)), + entityString); + + /// + /// 不可进行编辑,实体没有主键:{entityString} + /// + public static string CannotEdit_EntityHasNo_PrimaryKey(object entityString) + => string.Format( + GetString("CannotEdit_EntityHasNo_PrimaryKey", nameof(entityString)), + entityString); + + /// + /// 不可更新,数据未被跟踪,应该先查询 或者 Attach:{entityString} + /// + public static string CannotUpdate_DataShouldQueryOrAttach(object entityString) + => string.Format( + GetString("CannotUpdate_DataShouldQueryOrAttach", nameof(entityString)), + entityString); + + /// + /// 不可更新,实体没有主键:{entityString} + /// + public static string CannotUpdate_EntityHasNo_PrimaryKey(object entityString) + => string.Format( + GetString("CannotUpdate_EntityHasNo_PrimaryKey", nameof(entityString)), + entityString); + + /// + /// 不可更新,未设置主键的值:{entityString} + /// + public static string CannotUpdate_PrimaryKey_NotSet(object entityString) + => string.Format( + GetString("CannotUpdate_PrimaryKey_NotSet", nameof(entityString)), + entityString); + + /// + /// 不可更新,数据库不存在该记录:{entityString} + /// + public static string CannotUpdate_RecordDoesNotExist(object entityString) + => string.Format( + GetString("CannotUpdate_RecordDoesNotExist", nameof(entityString)), + entityString); + + /// + /// 请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql + /// + public static string ConfigureUseFreeSql + => GetString("ConfigureUseFreeSql"); + + /// + /// DbSet.AsType 参数错误,请传入正确的实体类型 + /// + public static string DbSetAsType_NotSupport_Object + => GetString("DbSetAsType_NotSupport_Object"); + + /// + /// 实体类型 {EntityTypeName} 无法转换为 {name},无法使用该方法 + /// + public static string EntityType_CannotConvert(object EntityTypeName, object name) + => string.Format( + GetString("EntityType_CannotConvert", nameof(EntityTypeName), nameof(name)), + EntityTypeName, name); + + /// + /// 实体类型 {EntityTypeName} 主键类型不为 {fullName},无法使用该方法 + /// + public static string EntityType_PrimaryKeyError(object EntityTypeName, object fullName) + => string.Format( + GetString("EntityType_PrimaryKeyError", nameof(EntityTypeName), nameof(fullName)), + EntityTypeName, fullName); + + /// + /// 实体类型 {EntityTypeName} 主键数量不为 1,无法使用该方法 + /// + public static string EntityType_PrimaryKeyIsNotOne(object EntityTypeName) + => string.Format( + GetString("EntityType_PrimaryKeyIsNotOne", nameof(EntityTypeName)), + EntityTypeName); + + /// + /// FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository + /// + public static string FailedSetFilter_NotBelongIRpository + => GetString("FailedSetFilter_NotBelongIRpository"); + + /// + /// 不可比较,实体没有主键:{entityString} + /// + public static string Incomparable_EntityHasNo_PrimaryKey(object entityString) + => string.Format( + GetString("Incomparable_EntityHasNo_PrimaryKey", nameof(entityString)), + entityString); + + /// + /// 不可比较,未设置主键的值:{entityString} + /// + public static string Incomparable_PrimaryKey_NotSet(object entityString) + => string.Format( + GetString("Incomparable_PrimaryKey_NotSet", nameof(entityString)), + entityString); + + /// + /// FreeSql.Repository Insert 失败,因为设置了过滤器 {filterKey}: {filterValueExpression},插入的数据不符合 {entityString} + /// + public static string InsertError_Filter(object filterKey, object filterValueExpression, object entityString) + => string.Format( + GetString("InsertError_Filter", nameof(filterKey), nameof(filterValueExpression), nameof(entityString)), + filterKey, filterValueExpression, entityString); + + /// + /// ISelect.AsType 参数不支持指定为 object + /// + public static string ISelectAsType_ParameterError + => GetString("ISelectAsType_ParameterError"); + + /// + /// {tableTypeFullName} 不存在属性 {propertyName} + /// + public static string NotFound_Property(object tableTypeFullName, object propertyName) + => string.Format( + GetString("NotFound_Property", nameof(tableTypeFullName), nameof(propertyName)), + tableTypeFullName, propertyName); + + /// + /// 找不到方法 DbSet<>.StatesRemoveByObjects + /// + public static string NotFoundMethod_StatesRemoveByObjects + => GetString("NotFoundMethod_StatesRemoveByObjects"); + + /// + /// 参数 data 类型错误 {entityTypeFullName} + /// + public static string ParameterDataTypeError(object entityTypeFullName) + => string.Format( + GetString("ParameterDataTypeError", nameof(entityTypeFullName)), + entityTypeFullName); + + /// + /// 参数错误 {param} + /// + public static string ParameterError(object param) + => string.Format( + GetString("ParameterError", nameof(param)), + param); + + /// + /// 参数错误 {param} 不能为 null + /// + public static string ParameterError_CannotBeNull(object param) + => string.Format( + GetString("ParameterError_CannotBeNull", nameof(param)), + param); + + /// + /// 参数错误 {many} 不是集合属性 + /// + public static string ParameterError_IsNot_CollectionProperties(object many) + => string.Format( + GetString("ParameterError_IsNot_CollectionProperties", nameof(many)), + many); + + /// + /// 参数错误 {many} 集合属性不存在 + /// + public static string ParameterError_NotFound_CollectionProperties(object many) + => string.Format( + GetString("ParameterError_NotFound_CollectionProperties", nameof(many)), + many); + + /// + /// 参数错误 {one} 属性不存在 + /// + public static string ParameterError_NotFound_Property(object one) + => string.Format( + GetString("ParameterError_NotFound_Property", nameof(one)), + one); + + /// + /// Propagation_Mandatory: 使用当前事务,如果没有当前事务,就抛出异常 + /// + public static string Propagation_Mandatory + => GetString("Propagation_Mandatory"); + + /// + /// Propagation_Never: 以非事务方式执行操作,如果当前事务存在则抛出异常 + /// + public static string Propagation_Never + => GetString("Propagation_Never"); + + /// + /// {tableTypeFullName} 类型的属性 {propertyName} 不是 OneToMany 或 ManyToMany 特性 + /// + public static string PropertyOfType_IsNot_OneToManyOrManyToMany(object tableTypeFullName, object propertyName) + => string.Format( + GetString("PropertyOfType_IsNot_OneToManyOrManyToMany", nameof(tableTypeFullName), nameof(propertyName)), + tableTypeFullName, propertyName); + + /// + /// 特别错误:批量添加失败,{dataType} 的返回数据,与添加的数目不匹配 + /// + public static string SpecialError_BatchAdditionFailed(object dataType) + => string.Format( + GetString("SpecialError_BatchAdditionFailed", nameof(dataType)), + dataType); + + /// + /// 特别错误:更新失败,数据未被跟踪:{entityString} + /// + public static string SpecialError_UpdateFailedDataNotTracked(object entityString) + => string.Format( + GetString("SpecialError_UpdateFailedDataNotTracked", nameof(entityString)), + entityString); + + /// + /// 已开启事务,不能禁用工作单元 + /// + public static string TransactionHasBeenStarted + => GetString("TransactionHasBeenStarted"); + + /// + /// {tableTypeFullName} 类型已设置属性 {propertyName} 忽略特性 + /// + public static string TypeHasSetProperty_IgnoreAttribute(object tableTypeFullName, object propertyName) + => string.Format( + GetString("TypeHasSetProperty_IgnoreAttribute", nameof(tableTypeFullName), nameof(propertyName)), + tableTypeFullName, propertyName); + + /// + /// {unitOfWorkManager} 构造参数 {fsql} 不能为 null + /// + public static string UnitOfWorkManager_Construction_CannotBeNull(object unitOfWorkManager, object fsql) + => string.Format( + GetString("UnitOfWorkManager_Construction_CannotBeNull", nameof(unitOfWorkManager), nameof(fsql)), + unitOfWorkManager, fsql); + + /// + /// FreeSql.Repository Update 失败,因为设置了过滤器 {filterKey}: {filterValueExpression},更新的数据不符合{entityString} + /// + public static string UpdateError_Filter(object filterKey, object filterValueExpression, object entityString) + => string.Format( + GetString("UpdateError_Filter", nameof(filterKey), nameof(filterValueExpression), nameof(entityString)), + filterKey, filterValueExpression, entityString); + + private static string GetString(string name, params string[] formatterNames) + { + var value = _resourceManager.GetString(name); + for (var i = 0; i < formatterNames.Length; i++) + { + value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}"); + } + + return value; + } + } +} + diff --git a/FreeSql.DbContext/Properties/DbContextStrings.Designer.tt b/FreeSql.DbContext/Properties/DbContextStrings.Designer.tt new file mode 100644 index 000000000..b8b9d8ad8 --- /dev/null +++ b/FreeSql.DbContext/Properties/DbContextStrings.Designer.tt @@ -0,0 +1,5 @@ +<# + Session["ResourceFile"] = "DbContextStrings.resx"; + Session["AccessModifier"] = "public"; +#> +<#@ include file="../../FreeSql/Properties/Resources.tt" #> \ No newline at end of file diff --git a/FreeSql.DbContext/Properties/DbContextStrings.en-US.resx b/FreeSql.DbContext/Properties/DbContextStrings.en-US.resx new file mode 100644 index 000000000..5b694b09c --- /dev/null +++ b/FreeSql.DbContext/Properties/DbContextStrings.en-US.resx @@ -0,0 +1,246 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + An error occurred in AddFreeDbContext, check that the construction parameters of {dbContextTypeName} have been injected correctly + + + Not addable, already exists in state management: {entityString} + + + Not addable, entity has no primary key: {entityString} + + + Not addable, no value for primary key set: {entityString} + + + Not addable, self-increasing attribute has value: {entityString} + + + Not attachable, entity has no primary key: {entityString} + + + Not attachable, no value for primary key set: {entityString} + + + Not deletable, data not tracked, should query first: {entityString} + + + Not deletable, entity has no primary key: {entityString} + + + Not deletable, no value for primary key set: {entityString} + + + Not editable, entity has no primary key: {entityString} + + + Not updatable, data not tracked, should be queried first or Attach:{entityString} + + + Not updatable, entity has no primary key: {entityString} + + + Not updatable, no value for primary key set: {entityString} + + + Not updatable, the record does not exist in the database: {entityString} + + + Please configure UseFreeSql in OnConfiguring or AddFreeDbContext + + + DbSet. AsType parameter error, please pass in the correct entity type + + + Entity type {EntityTypeName} cannot be converted to {name} and cannot use this method + + + Entity type {EntityTypeName} Primary key type is not {fullName} and cannot be used with this method + + + Entity type {EntityTypeName} Primary key number is not 1 and cannot be used with this method + + + FreeSql. Repository failed to set filter because object does not belong to IRepository + + + Not comparable, entity has no primary key: {entityString} + + + Non-comparable, no value for primary key set: {entityString} + + + FreeSql. Repository Insert failed because the filter {filterKey}: {filterValueExpression} was set and the inserted data does not conform to {entityString} + + + ISelect. AsType parameter does not support specifying as object + + + Property {propertyName} does not exist for {tableTypeFullName} + + + Method DbSet<> not found. StatesRemoveByObjects + + + Parameter data type error {entityTypeFullName} + + + Parameter error {param} + + + Parameter error {param} cannot be null + + + Parameter error {many} is not a collection property + + + Parameter error {many} Collection property does not exist + + + Parameter error {one} attribute does not exist + + + Propagation_ Mandatory: With the current transaction, throw an exception if there is no current transaction + + + Propagation_ Never: Perform the operation non-transactionally and throw an exception if the current transaction exists + + + Property {propertyName} of type {tableTypeFullName} is not OneToMany or ManyToMany attribute + + + Special error: Bulk add failed, {dataType} returned data, does not match the number added + + + Special error: Update failed, data not tracked: {entityString} + + + Transaction opened, unit of work cannot be disabled + + + The {tableTypeFullName} type has set the property {propertyName} Ignore the attribute + + + The {unitOfWorkManager} constructor parameter {fsql} cannot be null + + + FreeSql. Repository Update failed because the filter {filterKey}: {filterValueExpression} is set and the updated data does not conform to {entityString} + + \ No newline at end of file diff --git a/FreeSql.DbContext/Properties/DbContextStrings.resx b/FreeSql.DbContext/Properties/DbContextStrings.resx new file mode 100644 index 000000000..ce01210d9 --- /dev/null +++ b/FreeSql.DbContext/Properties/DbContextStrings.resx @@ -0,0 +1,246 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + AddFreeDbContext 发生错误,请检查 {dbContextTypeName} 的构造参数都已正确注入 + + + 不可添加,已存在于状态管理:{entityString} + + + 不可添加,实体没有主键:{entityString} + + + 不可添加,未设置主键的值:{entityString} + + + 不可添加,自增属性有值:{entityString} + + + 不可附加,实体没有主键:{entityString} + + + 不可附加,未设置主键的值:{entityString} + + + 不可删除,数据未被跟踪,应该先查询:{entityString} + + + 不可删除,实体没有主键:{entityString} + + + 不可删除,未设置主键的值:{entityString} + + + 不可进行编辑,实体没有主键:{entityString} + + + 不可更新,数据未被跟踪,应该先查询 或者 Attach:{entityString} + + + 不可更新,实体没有主键:{entityString} + + + 不可更新,未设置主键的值:{entityString} + + + 不可更新,数据库不存在该记录:{entityString} + + + 请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql + + + DbSet.AsType 参数错误,请传入正确的实体类型 + + + 实体类型 {EntityTypeName} 无法转换为 {name},无法使用该方法 + + + 实体类型 {EntityTypeName} 主键类型不为 {fullName},无法使用该方法 + + + 实体类型 {EntityTypeName} 主键数量不为 1,无法使用该方法 + + + FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository + + + 不可比较,实体没有主键:{entityString} + + + 不可比较,未设置主键的值:{entityString} + + + FreeSql.Repository Insert 失败,因为设置了过滤器 {filterKey}: {filterValueExpression},插入的数据不符合 {entityString} + + + ISelect.AsType 参数不支持指定为 object + + + {tableTypeFullName} 不存在属性 {propertyName} + + + 找不到方法 DbSet<>.StatesRemoveByObjects + + + 参数 data 类型错误 {entityTypeFullName} + + + 参数错误 {param} + + + 参数错误 {param} 不能为 null + + + 参数错误 {many} 不是集合属性 + + + 参数错误 {many} 集合属性不存在 + + + 参数错误 {one} 属性不存在 + + + Propagation_Mandatory: 使用当前事务,如果没有当前事务,就抛出异常 + + + Propagation_Never: 以非事务方式执行操作,如果当前事务存在则抛出异常 + + + {tableTypeFullName} 类型的属性 {propertyName} 不是 OneToMany 或 ManyToMany 特性 + + + 特别错误:批量添加失败,{dataType} 的返回数据,与添加的数目不匹配 + + + 特别错误:更新失败,数据未被跟踪:{entityString} + + + 已开启事务,不能禁用工作单元 + + + {tableTypeFullName} 类型已设置属性 {propertyName} 忽略特性 + + + {unitOfWorkManager} 构造参数 {fsql} 不能为 null + + + FreeSql.Repository Update 失败,因为设置了过滤器 {filterKey}: {filterValueExpression},更新的数据不符合{entityString} + + \ No newline at end of file diff --git a/FreeSql.DbContext/Repository/ContextSet/RepositoryDbSet.cs b/FreeSql.DbContext/Repository/ContextSet/RepositoryDbSet.cs index 159988a77..8490d1e8f 100644 --- a/FreeSql.DbContext/Repository/ContextSet/RepositoryDbSet.cs +++ b/FreeSql.DbContext/Repository/ContextSet/RepositoryDbSet.cs @@ -36,7 +36,7 @@ protected override IUpdate OrmUpdate(IEnumerable entitys) if (entitys != null) foreach (var entity in entitys) if (filter.Value.ExpressionDelegate?.Invoke(entity) == false) - throw new Exception($"FreeSql.Repository Update 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},更新的数据不符合 {_db.OrmOriginal.GetEntityString(_entityType, entity)}"); + throw new Exception(DbContextStrings.UpdateError_Filter(filter.Key, filter.Value.Expression, _db.OrmOriginal.GetEntityString(_entityType, entity))); update.Where(filter.Value.Expression); } var disableFilter = filters.Where(a => a.Value.IsEnabled == false).Select(a => a.Key).ToArray(); @@ -64,7 +64,7 @@ protected override IInsert OrmInsert(IEnumerable entitys) if (entitys != null) foreach (var entity in entitys) if (filter.Value.ExpressionDelegate?.Invoke(entity) == false) - throw new Exception($"FreeSql.Repository Insert 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},插入的数据不符合 {_db.OrmOriginal.GetEntityString(_entityType, entity)}"); + throw new Exception(DbContextStrings.InsertError_Filter(filter.Key, filter.Value.Expression, _db.OrmOriginal.GetEntityString(_entityType, entity))); } return insert; } diff --git a/FreeSql.DbContext/Repository/DataFilter/DataFilterUtil.cs b/FreeSql.DbContext/Repository/DataFilter/DataFilterUtil.cs index f626bc3af..ee5abb797 100644 --- a/FreeSql.DbContext/Repository/DataFilter/DataFilterUtil.cs +++ b/FreeSql.DbContext/Repository/DataFilter/DataFilterUtil.cs @@ -32,7 +32,7 @@ internal static void SetRepositoryDataFilter(object repos, Action new ConcurrentDictionary()); var newFilter = new Dictionary(); diff --git a/FreeSql.DbContext/Repository/Repository/BaseRepository.cs b/FreeSql.DbContext/Repository/Repository/BaseRepository.cs index 287ae2198..78c82be1b 100644 --- a/FreeSql.DbContext/Repository/Repository/BaseRepository.cs +++ b/FreeSql.DbContext/Repository/Repository/BaseRepository.cs @@ -186,12 +186,12 @@ public BaseRepository(IFreeSql fsql, Expression> filter, Fun TEntity CheckTKeyAndReturnIdEntity(TKey id) { var tb = _db.OrmOriginal.CodeFirst.GetTableByEntity(EntityType); - if (tb.Primarys.Length != 1) throw new Exception($"实体类型 {EntityType.Name} 主键数量不为 1,无法使用该方法"); - if (tb.Primarys[0].CsType.NullableTypeOrThis() != typeof(TKey).NullableTypeOrThis()) throw new Exception($"实体类型 {EntityType.Name} 主键类型不为 {typeof(TKey).FullName},无法使用该方法"); + if (tb.Primarys.Length != 1) throw new Exception(DbContextStrings.EntityType_PrimaryKeyIsNotOne(EntityType.Name)); + if (tb.Primarys[0].CsType.NullableTypeOrThis() != typeof(TKey).NullableTypeOrThis()) throw new Exception(DbContextStrings.EntityType_PrimaryKeyError(EntityType.Name, typeof(TKey).FullName)); var obj = Activator.CreateInstance(tb.Type); _db.OrmOriginal.SetEntityValueWithPropertyName(tb.Type, obj, tb.Primarys[0].CsName, id); - var ret = obj as TEntity; - if (ret == null) throw new Exception($"实体类型 {EntityType.Name} 无法转换为 {typeof(TEntity).Name},无法使用该方法"); + var ret = obj as TEntity; + if (ret == null) throw new Exception(DbContextStrings.EntityType_CannotConvert(EntityType.Name, typeof(TEntity).Name)); return ret; } diff --git a/FreeSql.DbContext/UnitOfWork/UnitOfWork.cs b/FreeSql.DbContext/UnitOfWork/UnitOfWork.cs index 93643e248..b2a8d368c 100644 --- a/FreeSql.DbContext/UnitOfWork/UnitOfWork.cs +++ b/FreeSql.DbContext/UnitOfWork/UnitOfWork.cs @@ -55,7 +55,7 @@ void ReturnObject() public void Close() { if (_tran != null) - throw new Exception("已开启事务,不能禁用工作单元"); + throw new Exception(DbContextStrings.TransactionHasBeenStarted); Enable = false; } diff --git a/FreeSql.DbContext/UnitOfWork/UnitOfWorkManager.cs b/FreeSql.DbContext/UnitOfWork/UnitOfWorkManager.cs index 42d7f2d36..375a0e4fd 100644 --- a/FreeSql.DbContext/UnitOfWork/UnitOfWorkManager.cs +++ b/FreeSql.DbContext/UnitOfWork/UnitOfWorkManager.cs @@ -22,7 +22,7 @@ public class UnitOfWorkManager : IDisposable public UnitOfWorkManager(IFreeSql fsql) { - if (fsql == null) throw new ArgumentNullException($"{nameof(UnitOfWorkManager)} 构造参数 {nameof(fsql)} 不能为 null"); + if (fsql == null) throw new ArgumentNullException(DbContextStrings.UnitOfWorkManager_Construction_CannotBeNull(nameof(UnitOfWorkManager), nameof(fsql))); _ormScoped = DbContextScopedFreeSql.Create(fsql, null, () => this.Current); } @@ -92,7 +92,7 @@ public IUnitOfWork Begin(Propagation propagation = Propagation.Required, Isolati { case Propagation.Required: return FindedUowCreateVirtual() ?? CreateUow(isolationLevel); case Propagation.Supports: return FindedUowCreateVirtual() ?? CreateUowNothing(_allUows.LastOrDefault()?.IsNotSupported ?? false); - case Propagation.Mandatory: return FindedUowCreateVirtual() ?? throw new Exception("Propagation_Mandatory: 使用当前事务,如果没有当前事务,就抛出异常"); + case Propagation.Mandatory: return FindedUowCreateVirtual() ?? throw new Exception(DbContextStrings.Propagation_Mandatory); case Propagation.NotSupported: return CreateUowNothing(true); case Propagation.Never: var isNotSupported = _allUows.LastOrDefault()?.IsNotSupported ?? false; @@ -100,7 +100,7 @@ public IUnitOfWork Begin(Propagation propagation = Propagation.Required, Isolati { for (var a = _rawUows.Count - 1; a >= 0; a--) if (_rawUows[a].Uow.GetOrBeginTransaction(false) != null) - throw new Exception("Propagation_Never: 以非事务方式执行操作,如果当前事务存在则抛出异常"); + throw new Exception(DbContextStrings.Propagation_Never); } return CreateUowNothing(isNotSupported); case Propagation.Nested: return CreateUow(isolationLevel); @@ -159,7 +159,7 @@ class RepoInfo { public IBaseRepository Repository; public IUnitOfWork OrginalUow; - + public RepoInfo(IBaseRepository repository) { this.Repository = repository; diff --git a/FreeSql.Tests/FreeSql.Tests/Properties/CoreStringsTests.cs b/FreeSql.Tests/FreeSql.Tests/Properties/CoreStringsTests.cs new file mode 100644 index 000000000..d9f547e6b --- /dev/null +++ b/FreeSql.Tests/FreeSql.Tests/Properties/CoreStringsTests.cs @@ -0,0 +1,657 @@ +using System.Threading; + +using Xunit; +using Xunit.Abstractions; + +namespace FreeSql.Tests.Properties +{ + public class CoreStringsTests + { + private readonly ITestOutputHelper output; + public CoreStringsTests(ITestOutputHelper output) + { + this.output = output; + Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); + Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); + } + [Fact] + public void AsTable_PropertyName_NotDateTimeTest() + { + string text = CoreStrings.AsTable_PropertyName_NotDateTime("1 "); + output.WriteLine(text); + } + + [Fact] + public void AsTable_PropertyName_FormatErrorTest() + { + string text = CoreStrings.AsTable_PropertyName_FormatError("1 "); + output.WriteLine(text); + } + + + [Fact] + public void Available_Failed_Get_ResourceTest() + { + string text = CoreStrings.Available_Failed_Get_Resource("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Available_Thrown_ExceptionTest() + { + string text = CoreStrings.Available_Thrown_Exception("1 "); + output.WriteLine(text); + } + + [Fact] + public void Bad_Expression_FormatTest() + { + string text = CoreStrings.Bad_Expression_Format("1 "); + output.WriteLine(text); + } + + [Fact] + public void Cannot_Be_NULL_NameTest() + { + string text = CoreStrings.Cannot_Be_NULL_Name("1 "); + output.WriteLine(text); + } + + [Fact] + public void Cannot_Match_PropertyTest() + { + string text = CoreStrings.Cannot_Match_Property("1 "); + output.WriteLine(text); + } + + [Fact] + public void Cannot_Resolve_ExpressionTreeTest() + { + string text = CoreStrings.Cannot_Resolve_ExpressionTree("1 "); + output.WriteLine(text); + } + + [Fact] + public void Custom_Expression_ParsingErrorTest() + { + string text = CoreStrings.Custom_Expression_ParsingError("1 "); + output.WriteLine(text); + } + + [Fact] + public void Custom_StaticMethodName_NotSet_DynamicFilterCustomTest() + { + string text = CoreStrings.Custom_StaticMethodName_NotSet_DynamicFilterCustom("1 "); + output.WriteLine(text); + } + + [Fact] + public void DataType_AsType_InconsistentTest() + { + string text = CoreStrings.DataType_AsType_Inconsistent("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void DbUpdateVersionException_RowLevelOptimisticLockTest() + { + string text = CoreStrings.DbUpdateVersionException_RowLevelOptimisticLock("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Duplicate_ColumnAttributeTest() + { + string text = CoreStrings.Duplicate_ColumnAttribute("1 "); + output.WriteLine(text); + } + + [Fact] + public void Duplicate_PropertyNameTest() + { + string text = CoreStrings.Duplicate_PropertyName("1 "); + output.WriteLine(text); + } + + [Fact] + public void Entity_Must_Primary_KeyTest() + { + string text = CoreStrings.Entity_Must_Primary_Key("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Entity_MySQL_VersionsBelow8_NotSupport_Multiple_PrimaryKeysTest() + { + string text = CoreStrings.Entity_MySQL_VersionsBelow8_NotSupport_Multiple_PrimaryKeys("1 "); + output.WriteLine(text); + } + + [Fact] + public void Entity_NotParentChild_RelationshipTest() + { + string text = CoreStrings.Entity_NotParentChild_Relationship("1 "); + output.WriteLine(text); + } + + [Fact] + public void Expression_Error_Use_ParameterExpressionTest() + { + string text = CoreStrings.Expression_Error_Use_ParameterExpression("1 "); + output.WriteLine(text); + } + + [Fact] + public void Expression_Error_Use_Successive_MemberAccess_TypeTest() + { + string text = CoreStrings.Expression_Error_Use_Successive_MemberAccess_Type("1 "); + output.WriteLine(text); + } + + [Fact] + public void ExpressionTree_Convert_Type_ErrorTest() + { + string text = CoreStrings.ExpressionTree_Convert_Type_Error("1", "2", "3", "4 "); + output.WriteLine(text); + } + + [Fact] + public void Failed_SubTable_FieldValueTest() + { + string text = CoreStrings.Failed_SubTable_FieldValue("1 "); + output.WriteLine(text); + } + + [Fact] + public void Functions_AsTable_NotImplementedTest() + { + string text = CoreStrings.Functions_AsTable_NotImplemented("1 "); + output.WriteLine(text); + } + + [Fact] + public void Generated_Same_SubTableTest() + { + string text = CoreStrings.Generated_Same_SubTable("1 "); + output.WriteLine(text); + } + + [Fact] + public void GetPrimarys_ParameterError_IsNotDictKeyTest() + { + string text = CoreStrings.GetPrimarys_ParameterError_IsNotDictKey("1 "); + output.WriteLine(text); + } + + [Fact] + public void Has_Specified_Cannot_Specified_SecondTest() + { + string text = CoreStrings.Has_Specified_Cannot_Specified_Second("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Ignored_Check_Confirm_PublicGetSetTest() + { + string text = CoreStrings.Ignored_Check_Confirm_PublicGetSet("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void IncludeMany_NotValid_NavigationTest() + { + string text = CoreStrings.IncludeMany_NotValid_Navigation("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void IncludeMany_ParameterError_OnlyUseOneParameterTest() + { + string text = CoreStrings.IncludeMany_ParameterError_OnlyUseOneParameter("1 "); + output.WriteLine(text); + } + + [Fact] + public void IncludeMany_ParameterError_Select_ReturnConsistentTypeTest() + { + string text = CoreStrings.IncludeMany_ParameterError_Select_ReturnConsistentType("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void IncludeMany_ParameterTypeErrorTest() + { + string text = CoreStrings.IncludeMany_ParameterTypeError("1 "); + output.WriteLine(text); + } + + [Fact] + public void InsertInto_No_Property_SelectedTest() + { + string text = CoreStrings.InsertInto_No_Property_Selected("1 "); + output.WriteLine(text); + } + + [Fact] + public void InsertInto_TypeErrorTest() + { + string text = CoreStrings.InsertInto_TypeError("1 "); + output.WriteLine(text); + } + + [Fact] + public void InsertOrUpdate_Must_Primary_KeyTest() + { + string text = CoreStrings.InsertOrUpdate_Must_Primary_Key("1 "); + output.WriteLine(text); + } + + [Fact] + public void InsertOrUpdate_NotSuport_Generic_UseEntityTest() + { + string text = CoreStrings.InsertOrUpdate_NotSuport_Generic_UseEntity("1 "); + output.WriteLine(text); + } + + [Fact] + public void LazyLoading_CompilationErrorTest() + { + string text = CoreStrings.LazyLoading_CompilationError("1", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void LazyLoading_EntityMustDeclarePublicTest() + { + string text = CoreStrings.LazyLoading_EntityMustDeclarePublic("1 "); + output.WriteLine(text); + } + + [Fact] + public void ManyToMany_NotFound_CorrespondingFieldTest() + { + string text = CoreStrings.ManyToMany_NotFound_CorrespondingField("1", "2", "2", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void ManyToMany_ParsingError_EntityMissing_PrimaryKeyTest() + { + string text = CoreStrings.ManyToMany_ParsingError_EntityMissing_PrimaryKey("1", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void ManyToMany_ParsingError_EntityMustHas_NavigateCollectionTest() + { + string text = CoreStrings.ManyToMany_ParsingError_EntityMustHas_NavigateCollection("1", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void ManyToMany_ParsingError_InconsistentTypeTest() + { + string text = CoreStrings.ManyToMany_ParsingError_InconsistentType("1", "2", "2", "2", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void ManyToMany_ParsingError_IntermediateClass_ErrorMessageTest() + { + string text = CoreStrings.ManyToMany_ParsingError_IntermediateClass_ErrorMessage("1", "2", "2", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void ManyToMany_ParsingError_IntermediateClass_NotManyToOne_OneToOneTest() + { + string text = CoreStrings.ManyToMany_ParsingError_IntermediateClass_NotManyToOne_OneToOne("1", "2", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Mapping_Exception_HasNo_SamePropertyNameTest() + { + string text = CoreStrings.Mapping_Exception_HasNo_SamePropertyName("1 "); + output.WriteLine(text); + } + + [Fact] + public void Missing_FreeSqlProvider_PackageTest() + { + string text = CoreStrings.Missing_FreeSqlProvider_Package("1 "); + output.WriteLine(text); + } + + [Fact] + public void Missing_FreeSqlProvider_Package_ReasonTest() + { + string text = CoreStrings.Missing_FreeSqlProvider_Package_Reason("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Navigation_Bind_Number_DifferentTest() + { + string text = CoreStrings.Navigation_Bind_Number_Different("1", "2", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Navigation_Missing_AsSelectTest() + { + string text = CoreStrings.Navigation_Missing_AsSelect("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Navigation_Missing_SetPropertyTest() + { + string text = CoreStrings.Navigation_Missing_SetProperty("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Navigation_NotFound_CorrespondingFieldTest() + { + string text = CoreStrings.Navigation_NotFound_CorrespondingField("1", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Navigation_ParsingError_EntityMissingPrimaryKeyTest() + { + string text = CoreStrings.Navigation_ParsingError_EntityMissingPrimaryKey("1", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Navigation_ParsingError_InconsistentTypeTest() + { + string text = CoreStrings.Navigation_ParsingError_InconsistentType("1", "2", "2", "2", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Navigation_ParsingError_NotFound_PropertyTest() + { + string text = CoreStrings.Navigation_ParsingError_NotFound_Property("1", "2", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void NoPrimaryKey_UseSetDtoTest() + { + string text = CoreStrings.NoPrimaryKey_UseSetDto("1 "); + output.WriteLine(text); + } + + [Fact] + public void Not_Implemented_ExpressionTest() + { + string text = CoreStrings.Not_Implemented_Expression("1 "); + output.WriteLine(text); + } + + [Fact] + public void Not_Implemented_Expression_ParameterUseConstantTest() + { + string text = CoreStrings.Not_Implemented_Expression_ParameterUseConstant("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Not_Implemented_Expression_UseAsSelectTest() + { + string text = CoreStrings.Not_Implemented_Expression_UseAsSelect("1", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Not_Implemented_NameTest() + { + string text = CoreStrings.Not_Implemented_Name("1 "); + output.WriteLine(text); + } + + [Fact] + public void Not_Support_OrderByRandomTest() + { + string text = CoreStrings.Not_Support_OrderByRandom("1 "); + output.WriteLine(text); + } + + [Fact] + public void Not_Valid_Navigation_PropertyTest() + { + string text = CoreStrings.Not_Valid_Navigation_Property("1 "); + output.WriteLine(text); + } + + [Fact] + public void NotFound_ColumnTest() + { + string text = CoreStrings.NotFound_Column("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void NotFound_CsName_ColumnTest() + { + string text = CoreStrings.NotFound_Column("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void NotFound_PropertyTest() + { + string text = CoreStrings.NotFound_Property("1 "); + output.WriteLine(text); + } + + [Fact] + public void NotFound_PropertyNameTest() + { + string text = CoreStrings.NotFound_PropertyName("1 "); + output.WriteLine(text); + } + + [Fact] + public void NotFound_ReflectionTest() + { + string text = CoreStrings.NotFound_Reflection("1 "); + output.WriteLine(text); + } + + [Fact] + public void NotFound_Static_MethodNameTest() + { + string text = CoreStrings.NotFound_Static_MethodName("1 "); + output.WriteLine(text); + } + + [Fact] + public void NotFound_Table_Property_AsTableTest() + { + string text = CoreStrings.NotFound_Table_Property_AsTable("1 "); + output.WriteLine(text); + } + + [Fact] + public void ObjectPool_Get_TimeoutTest() + { + string text = CoreStrings.ObjectPool_Get_Timeout("1", "2", "3"); + output.WriteLine(text); + } + + [Fact] + public void ObjectPool_GetAsync_Queue_LongTest() + { + string text = CoreStrings.ObjectPool_GetAsync_Queue_Long("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void OneToMany_NotFound_CorrespondingFieldTest() + { + string text = CoreStrings.OneToMany_NotFound_CorrespondingField("1", "2", "2", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void OneToMany_ParsingError_InconsistentTypeTest() + { + string text = CoreStrings.OneToMany_ParsingError_InconsistentType("1", "2", "2", "2", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void OneToMany_UseNavigateTest() + { + string text = CoreStrings.OneToMany_UseNavigate("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void ParameterError_NotValid_CollectionTest() + { + string text = CoreStrings.ParameterError_NotValid_Collection("1 "); + output.WriteLine(text); + } + + [Fact] + public void ParameterError_NotValid_NavigationTest() + { + string text = CoreStrings.ParameterError_NotValid_Navigation("1 "); + output.WriteLine(text); + } + + [Fact] + public void ParameterError_NotValid_PropertyNameTest() + { + string text = CoreStrings.ParameterError_NotValid_PropertyName("1", "2", "2 "); + output.WriteLine(text); + } + + [Fact] + public void ParameterError_NotValid_UseCommasTest() + { + string text = CoreStrings.ParameterError_NotValid_UseCommas("1 "); + output.WriteLine(text); + } + + [Fact] + public void Parsing_FailedTest() + { + string text = CoreStrings.Parsing_Failed("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Policy_ObjectPool_DisposeTest() + { + string text = CoreStrings.Policy_ObjectPool_Dispose("1 "); + output.WriteLine(text); + } + + [Fact] + public void Policy_Status_NotAvailableTest() + { + string text = CoreStrings.Policy_Status_NotAvailable("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void Properties_AsRowLock_Must_Numeric_ByteTest() + { + string text = CoreStrings.Properties_AsRowLock_Must_Numeric_Byte("1 "); + output.WriteLine(text); + } + + [Fact] + public void Property_Cannot_FindTest() + { + string text = CoreStrings.Property_Cannot_Find("1 "); + output.WriteLine(text); + } + + [Fact] + public void Set_Column_IsNullable_FalseTest() + { + string text = CoreStrings.Set_Column_IsNullable_False("1 "); + output.WriteLine(text); + } + + [Fact] + public void SubTableFieldValue_CannotLessThenTest() + { + string text = CoreStrings.SubTableFieldValue_CannotLessThen("1", "2 "); + output.WriteLine(text); + } + + [Fact] + public void SubTableFieldValue_NotConvertDateTimeTest() + { + string text = CoreStrings.SubTableFieldValue_NotConvertDateTime("1 "); + output.WriteLine(text); + } + + [Fact] + public void SubTableFieldValue_NotMatchTableTest() + { + string text = CoreStrings.SubTableFieldValue_NotConvertDateTime("1 "); + output.WriteLine(text); + } + + + [Fact] + public void Type_AsType_Parameter_ErrorTest() + { + string text = CoreStrings.Type_AsType_Parameter_Error("1 "); + output.WriteLine(text); + } + + [Fact] + public void Type_Cannot_Access_ConstructorTest() + { + string text = CoreStrings.Type_Cannot_Access_Constructor("1 "); + output.WriteLine(text); + } + + [Fact] + public void Type_Error_NameTest() + { + string text = CoreStrings.Type_Error_Name("1 "); + output.WriteLine(text); + } + + [Fact] + public void TypeAsType_NotSupport_ObjectTest() + { + string text = CoreStrings.TypeAsType_NotSupport_Object("1 "); + output.WriteLine(text); + } + + [Fact] + public void TypeError_CannotUse_IncludeManyTest() + { + string text = CoreStrings.TypeError_CannotUse_IncludeMany("1 "); + output.WriteLine(text); + } + + [Fact] + public void Unable_Parse_ExpressionTest() + { + string text = CoreStrings.Unable_Parse_Expression("1 "); + output.WriteLine(text); + } + + [Fact] + public void Unable_Parse_ExpressionMethodTest() + { + string text = CoreStrings.Unable_Parse_ExpressionMethod("1 "); + output.WriteLine(text); + } + + } +} \ No newline at end of file diff --git a/FreeSql.Tests/FreeSql.Tests/Properties/DbContextStringsTests.cs b/FreeSql.Tests/FreeSql.Tests/Properties/DbContextStringsTests.cs new file mode 100644 index 000000000..cdfa205cb --- /dev/null +++ b/FreeSql.Tests/FreeSql.Tests/Properties/DbContextStringsTests.cs @@ -0,0 +1,260 @@ +using Xunit; +using Xunit.Abstractions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Threading; + +namespace FreeSql.Tests.Properties +{ + public class DbContextStringsTests + { + private readonly ITestOutputHelper output; + public DbContextStringsTests(ITestOutputHelper output) + { + this.output = output; + Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); + Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); + } + + [Fact] + public void AddFreeDbContextError_CheckConstructionTest() + { + string text = DbContextStrings.AddFreeDbContextError_CheckConstruction("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotAdd_AlreadyExistsInStateManagementTest() + { + string text = DbContextStrings.CannotAdd_AlreadyExistsInStateManagement("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotAdd_EntityHasNo_PrimaryKeyTest() + { + string text = DbContextStrings.CannotAdd_EntityHasNo_PrimaryKey("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotAdd_PrimaryKey_NotSetTest() + { + string text = DbContextStrings.CannotAdd_PrimaryKey_NotSet("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotAdd_SelfIncreasingHasValueTest() + { + string text = DbContextStrings.CannotAdd_SelfIncreasingHasValue("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotAttach_EntityHasNo_PrimaryKeyTest() + { + string text = DbContextStrings.CannotAttach_EntityHasNo_PrimaryKey("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotAttach_PrimaryKey_NotSetTest() + { + string text = DbContextStrings.CannotAttach_PrimaryKey_NotSet("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotDelete_DataNotTracked_ShouldQueryTest() + { + string text = DbContextStrings.CannotDelete_DataNotTracked_ShouldQuery("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotDelete_EntityHasNo_PrimaryKeyTest() + { + string text = DbContextStrings.CannotDelete_EntityHasNo_PrimaryKey("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotDelete_PrimaryKey_NotSetTest() + { + string text = DbContextStrings.CannotDelete_PrimaryKey_NotSet("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotEdit_EntityHasNo_PrimaryKeyTest() + { + string text = DbContextStrings.CannotEdit_EntityHasNo_PrimaryKey("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotUpdate_DataShouldQueryOrAttachTest() + { + string text = DbContextStrings.CannotUpdate_DataShouldQueryOrAttach("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotUpdate_EntityHasNo_PrimaryKeyTest() + { + string text = DbContextStrings.CannotUpdate_EntityHasNo_PrimaryKey("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotUpdate_PrimaryKey_NotSetTest() + { + string text = DbContextStrings.CannotUpdate_PrimaryKey_NotSet("1"); + output.WriteLine(text); + } + + [Fact] + public void CannotUpdate_RecordDoesNotExistTest() + { + string text = DbContextStrings.CannotUpdate_RecordDoesNotExist("1"); + output.WriteLine(text); + } + + [Fact] + public void EntityType_CannotConvertTest() + { + string text = DbContextStrings.EntityType_CannotConvert("1", "2"); + output.WriteLine(text); + } + + [Fact] + public void EntityType_PrimaryKeyErrorTest() + { + string text = DbContextStrings.EntityType_PrimaryKeyError("1", "2"); + output.WriteLine(text); + } + + [Fact] + public void EntityType_PrimaryKeyIsNotOneTest() + { + string text = DbContextStrings.EntityType_PrimaryKeyIsNotOne("1"); + output.WriteLine(text); + } + + [Fact] + public void Incomparable_EntityHasNo_PrimaryKeyTest() + { + string text = DbContextStrings.Incomparable_EntityHasNo_PrimaryKey("1"); + output.WriteLine(text); + } + + [Fact] + public void Incomparable_PrimaryKey_NotSetTest() + { + string text = DbContextStrings.Incomparable_PrimaryKey_NotSet("1"); + output.WriteLine(text); + } + + [Fact] + public void InsertError_FilterTest() + { + string text = DbContextStrings.InsertError_Filter("1", "2", "2"); + output.WriteLine(text); + } + + [Fact] + public void NotFound_PropertyTest() + { + string text = DbContextStrings.NotFound_Property("1", "2"); + output.WriteLine(text); + } + + [Fact] + public void ParameterDataTypeErrorTest() + { + string text = DbContextStrings.ParameterDataTypeError("1"); + output.WriteLine(text); + } + + [Fact] + public void ParameterErrorTest() + { + string text = DbContextStrings.ParameterError("1"); + output.WriteLine(text); + } + + [Fact] + public void ParameterError_CannotBeNullTest() + { + string text = DbContextStrings.ParameterError_CannotBeNull("1"); + output.WriteLine(text); + } + + [Fact] + public void ParameterError_IsNot_CollectionPropertiesTest() + { + string text = DbContextStrings.ParameterError_IsNot_CollectionProperties("1"); + output.WriteLine(text); + } + + [Fact] + public void ParameterError_NotFound_CollectionPropertiesTest() + { + string text = DbContextStrings.ParameterError_NotFound_CollectionProperties("1"); + output.WriteLine(text); + } + + [Fact] + public void ParameterError_NotFound_PropertyTest() + { + string text = DbContextStrings.ParameterError_NotFound_Property("1"); + output.WriteLine(text); + } + + [Fact] + public void PropertyOfType_IsNot_OneToManyOrManyToManyTest() + { + string text = DbContextStrings.PropertyOfType_IsNot_OneToManyOrManyToMany("1", "2"); + output.WriteLine(text); + } + + [Fact] + public void SpecialError_BatchAdditionFailedTest() + { + string text = DbContextStrings.SpecialError_BatchAdditionFailed("1"); + output.WriteLine(text); + } + + [Fact] + public void SpecialError_UpdateFailedDataNotTrackedTest() + { + string text = DbContextStrings.SpecialError_UpdateFailedDataNotTracked("1"); + output.WriteLine(text); + } + + [Fact] + public void TypeHasSetProperty_IgnoreAttributeTest() + { + string text = DbContextStrings.TypeHasSetProperty_IgnoreAttribute("1", "2"); + output.WriteLine(text); + } + + [Fact] + public void UnitOfWorkManager_Construction_CannotBeNullTest() + { + string text = DbContextStrings.UnitOfWorkManager_Construction_CannotBeNull("1", "2"); + output.WriteLine(text); + } + + [Fact] + public void UpdateError_FilterTest() + { + string text = DbContextStrings.UpdateError_Filter("1", "2", "3"); + output.WriteLine(text); + } + } +} \ No newline at end of file diff --git a/FreeSql.Tests/FreeSql.Tests/UnitTest5.cs b/FreeSql.Tests/FreeSql.Tests/UnitTest5.cs index 19335b530..7593ec8c4 100644 --- a/FreeSql.Tests/FreeSql.Tests/UnitTest5.cs +++ b/FreeSql.Tests/FreeSql.Tests/UnitTest5.cs @@ -16,6 +16,11 @@ namespace FreeSql.Tests { public class UnitTest5 { + [Fact] + public void AsTable_PropertyName_FormatErrorTest1() + { + CoreStrings.AsTable_PropertyName_FormatError("astable"); + } // DTO public class TestDto { diff --git a/FreeSql.sln b/FreeSql.sln index 2fac28703..f713110d9 100644 --- a/FreeSql.sln +++ b/FreeSql.sln @@ -688,5 +688,7 @@ Global EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {089687FD-5D25-40AB-BA8A-A10D1E137F98} + RESX_PrefixTranslations = False + RESX_NeutralResourcesLanguage = zh-Hans EndGlobalSection EndGlobal diff --git a/FreeSql/DataAnnotations/TableAttribute.cs b/FreeSql/DataAnnotations/TableAttribute.cs index d6d2a4f38..7b35a6ed1 100644 --- a/FreeSql/DataAnnotations/TableAttribute.cs +++ b/FreeSql/DataAnnotations/TableAttribute.cs @@ -47,14 +47,14 @@ internal void ParseAsTable(TableInfo tb) { var atm = Regex.Match(AsTable, @"([\w_\d]+)\s*=\s*(\d\d\d\d)\s*\-\s*(\d\d?)\s*\-\s*(\d\d?)\s*\((\d+)\s*(year|month|day|hour)\)", RegexOptions.IgnoreCase); if (atm.Success == false) - throw new Exception($"[Table(AsTable = \"{AsTable}\")] 特性值格式错误"); + throw new Exception(CoreStrings.AsTable_PropertyName_FormatError(AsTable)); tb.AsTableColumn = tb.Columns.TryGetValue(atm.Groups[1].Value, out var trycol) ? trycol : - tb.ColumnsByCs.TryGetValue(atm.Groups[1].Value, out trycol) ? trycol : throw new Exception($"[Table(AsTable = xx)] 设置的属性名 {atm.Groups[1].Value} 不存在"); + tb.ColumnsByCs.TryGetValue(atm.Groups[1].Value, out trycol) ? trycol : throw new Exception(CoreStrings.NotFound_Table_Property_AsTable(atm.Groups[1].Value)); if (tb.AsTableColumn.Attribute.MapType.NullableTypeOrThis() != typeof(DateTime)) { tb.AsTableColumn = null; - throw new Exception($"[Table(AsTable = xx)] 设置的属性名 {atm.Groups[1].Value} 不是 DateTime 类型"); + throw new Exception(CoreStrings.AsTable_PropertyName_NotDateTime(atm.Groups[1].Value)); } int.TryParse(atm.Groups[5].Value, out var atm5); string atm6 = atm.Groups[6].Value.ToLower(); @@ -67,7 +67,7 @@ internal void ParseAsTable(TableInfo tb) case "day": return dt.AddDays(atm5); case "hour": return dt.AddHours(atm5); } - throw new NotImplementedException($"AsTable 未实现的功能 {AsTable}"); + throw new NotImplementedException(CoreStrings.Functions_AsTable_NotImplemented(AsTable)); }); } } @@ -94,13 +94,13 @@ class DateTimeAsTableImpl : IAsTable public DateTimeAsTableImpl(string tableName, DateTime beginTime, Func nextTimeFunc) { - if (nextTimeFunc == null) throw new ArgumentException($"nextTimeFunc 不可以为 null"); + if (nextTimeFunc == null) throw new ArgumentException(CoreStrings.Cannot_Be_NULL_Name("nextTimeFunc")); beginTime = beginTime.Date; //日期部分作为开始 _beginTime = beginTime; _nextTimeFunc = nextTimeFunc; _tableName = tableName; _tableNameFormat = _regTableNameFormat.Match(tableName); - if (string.IsNullOrEmpty(_tableNameFormat.Groups[1].Value)) throw new ArgumentException("tableName 格式错误,示例:“log_{yyyyMMdd}”"); + if (string.IsNullOrEmpty(_tableNameFormat.Groups[1].Value)) throw new ArgumentException(CoreStrings.TableName_Format_Error("yyyyMMdd")); ExpandTable(beginTime, DateTime.Now); } @@ -114,7 +114,7 @@ void ExpandTable(DateTime beginTime, DateTime endTime) { var dtstr = beginTime.ToString(_tableNameFormat.Groups[1].Value); var name = _tableName.Replace(_tableNameFormat.Groups[0].Value, dtstr); - if (_allTables.Contains(name)) throw new ArgumentException($"tableName:{_tableName} 生成了相同的分表名"); + if (_allTables.Contains(name)) throw new ArgumentException(CoreStrings.Generated_Same_SubTable(_tableName)); _allTables.Insert(0, name); _allTablesTime.Insert(0, beginTime); _lastTime = beginTime; @@ -124,26 +124,26 @@ void ExpandTable(DateTime beginTime, DateTime endTime) } DateTime ParseColumnValue(object columnValue) { - if (columnValue == null) throw new Exception($"分表字段值不能为 null"); + if (columnValue == null) throw new Exception(CoreStrings.SubTableFieldValue_IsNotNull); DateTime dt; if (columnValue is DateTime || columnValue is DateTime?) dt = (DateTime)columnValue; else if (columnValue is string) { - if (DateTime.TryParse(string.Concat(columnValue), out dt) == false) throw new Exception($"分表字段值 \"{columnValue}\" 不能转化成 DateTime"); + if (DateTime.TryParse(string.Concat(columnValue), out dt) == false) throw new Exception(CoreStrings.SubTableFieldValue_NotConvertDateTime(columnValue)); } else if (columnValue is int || columnValue is long) { dt = new DateTime(1970, 1, 1).AddSeconds((double)columnValue); } - else throw new Exception($"分表字段值 \"{columnValue}\" 不能转化成 DateTime"); + else throw new Exception(CoreStrings.SubTableFieldValue_NotConvertDateTime(columnValue)); return dt; } public string GetTableNameByColumnValue(object columnValue, bool autoExpand = false) { var dt = ParseColumnValue(columnValue); - if (dt < _beginTime) throw new Exception($"分表字段值 \"{dt.ToString("yyyy-MM-dd HH:mm:ss")}\" 不能小于 \"{_beginTime.ToString("yyyy-MM-dd HH:mm:ss")} \""); + if (dt < _beginTime) throw new Exception(CoreStrings.SubTableFieldValue_CannotLessThen(dt.ToString("yyyy-MM-dd HH:mm:ss"), _beginTime.ToString("yyyy-MM-dd HH:mm:ss"))); var tmpTime = _nextTimeFunc(_lastTime); if (dt >= tmpTime && autoExpand) { @@ -157,7 +157,7 @@ public string GetTableNameByColumnValue(object columnValue, bool autoExpand = fa if (dt >= _allTablesTime[a]) return _allTables[a]; } - throw new Exception($"分表字段值 \"{dt.ToString("yyyy-MM-dd HH:mm:ss")}\" 未匹配到分表名"); + throw new Exception(CoreStrings.SubTableFieldValue_NotMatchTable(dt.ToString("yyyy-MM-dd HH:mm:ss"))); } public string[] GetTableNamesByColumnValueRange(object columnValue1, object columnValue2) { @@ -279,7 +279,7 @@ public string[] GetTableNamesBySqlWhere(string sqlWhere, List dbPar { var val1 = LocalGetParamValue(m.Groups[1].Value); var val2 = LocalGetParamValue(m.Groups[2].Value); - if (val1 == null || val2 == null) throw new Exception($"未能解析分表字段值 {sqlWhere}"); + if (val1 == null || val2 == null) throw new Exception(CoreStrings.Failed_SubTable_FieldValue(sqlWhere)); return GetTableNamesByColumnValueRange(val1, val2); } m = regs[11].Match(newSqlWhere); @@ -287,14 +287,14 @@ public string[] GetTableNamesBySqlWhere(string sqlWhere, List dbPar { var val1 = LocalGetParamValue(m.Groups[2].Value); var val2 = LocalGetParamValue(m.Groups[4].Value); - if (val1 == null || val2 == null) throw new Exception($"未能解析分表字段值 {sqlWhere}"); + if (val1 == null || val2 == null) throw new Exception(CoreStrings.Failed_SubTable_FieldValue(sqlWhere)); return LocalGetTables(m.Groups[1].Value, m.Groups[3].Value, ParseColumnValue(val1), ParseColumnValue(val2)); } m = regs[13].Match(newSqlWhere); if (m.Success) { var val1 = LocalGetParamValue(m.Groups[2].Value); - if (val1 == null) throw new Exception($"未能解析分表字段值 {sqlWhere}"); + if (val1 == null) throw new Exception(CoreStrings.Failed_SubTable_FieldValue(sqlWhere)); return LocalGetTables2(m.Groups[1].Value, ParseColumnValue(val1)); } return AllTables; diff --git a/FreeSql/DataAnnotations/TableFluent.cs b/FreeSql/DataAnnotations/TableFluent.cs index 5a9c25e7c..5ae941723 100644 --- a/FreeSql/DataAnnotations/TableFluent.cs +++ b/FreeSql/DataAnnotations/TableFluent.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Data.Common; using System.Linq; using System.Linq.Expressions; using System.Reflection; @@ -47,7 +48,7 @@ public TableFluent DisableSyncStructure(bool value) public ColumnFluent Property(string proto) { - if (_properties.TryGetValue(proto, out var tryProto) == false) throw new KeyNotFoundException($"找不到属性名 {proto}"); + if (_properties.TryGetValue(proto, out var tryProto) == false) throw new KeyNotFoundException(CoreStrings.NotFound_PropertyName(proto)); var col = _table._columns.GetOrAdd(tryProto.Name, name => new ColumnAttribute { Name = proto }); return new ColumnFluent(col, tryProto, _entityType); } @@ -61,7 +62,7 @@ public ColumnFluent Property(string proto) /// public TableFluent Navigate(string proto, string bind, Type manyToMany = null) { - if (_properties.TryGetValue(proto, out var tryProto) == false) throw new KeyNotFoundException($"找不到属性名 {proto}"); + if (_properties.TryGetValue(proto, out var tryProto) == false) throw new KeyNotFoundException(CoreStrings.NotFound_Property(proto)); var nav = new NavigateAttribute { Bind = bind, ManyToMany = manyToMany }; _table._navigates.AddOrUpdate(tryProto.Name, nav, (name, old) => nav); return this; @@ -129,12 +130,12 @@ public ColumnFluent Property(Expression> column) var exp = column?.Body; if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand; var proto = (exp as MemberExpression)?.Member; - if (proto == null) throw new FormatException($"错误的表达式格式 {column}"); + if (proto == null) throw new FormatException(CoreStrings.Bad_Expression_Format(column)); return Property(proto.Name); } public ColumnFluent Property(string proto) { - if (_properties.TryGetValue(proto, out var tryProto) == false) throw new KeyNotFoundException($"找不到属性名 {proto}"); + if (_properties.TryGetValue(proto, out var tryProto) == false) throw new KeyNotFoundException(CoreStrings.NotFound_PropertyName(proto)); var col = _table._columns.GetOrAdd(tryProto.Name, name => new ColumnAttribute { Name = proto }); return new ColumnFluent(col, tryProto, typeof(T)); } @@ -152,12 +153,12 @@ public TableFluent Navigate(Expression> proto, string var exp = proto?.Body; if (exp.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand; var member = (exp as MemberExpression)?.Member; - if (member == null) throw new FormatException($"错误的表达式格式 {proto}"); + if (member == null) throw new FormatException(CoreStrings.Bad_Expression_Format(proto)); return Navigate(member.Name, bind, manyToMany); } public TableFluent Navigate(string proto, string bind, Type manyToMany = null) { - if (_properties.TryGetValue(proto, out var tryProto) == false) throw new KeyNotFoundException($"找不到属性名 {proto}"); + if (_properties.TryGetValue(proto, out var tryProto) == false) throw new KeyNotFoundException(CoreStrings.NotFound_PropertyName(proto)); var nav = new NavigateAttribute { Bind = bind, ManyToMany = manyToMany }; _table._navigates.AddOrUpdate(tryProto.Name, nav, (name, old) => nav); return this; diff --git a/FreeSql/Extensions/AdoNetExtensions.cs b/FreeSql/Extensions/AdoNetExtensions.cs index 73b0d0155..51c7e1969 100644 --- a/FreeSql/Extensions/AdoNetExtensions.cs +++ b/FreeSql/Extensions/AdoNetExtensions.cs @@ -13,8 +13,8 @@ public static class AdoNetExtensions static object _dicCurdLock = new object(); static IFreeSql GetCrud(IDbConnection dbconn) { - if (dbconn == null) throw new ArgumentNullException($"{nameof(dbconn)} 不能为 null"); - if (dbconn.ConnectionString == null) throw new ArgumentNullException($"{nameof(dbconn)}.ConnectionString 不能为 null"); + if (dbconn == null) throw new ArgumentNullException($"{nameof(dbconn)} {CoreStrings.Cannot_Be_NULL}"); + if (dbconn.ConnectionString == null) throw new ArgumentNullException($"{nameof(dbconn)}.ConnectionString {CoreStrings.Cannot_Be_NULL}"); Type dbconType = dbconn.GetType(); var connType = dbconType.UnderlyingSystemType; if (_dicCurd.TryGetValue(dbconn.ConnectionString, out var fsql)) return fsql; @@ -25,46 +25,46 @@ static IFreeSql GetCrud(IDbConnection dbconn) case "MySqlConnection": providerType = Type.GetType("FreeSql.MySql.MySqlProvider`1,FreeSql.Provider.MySql")?.MakeGenericType(connType); if (providerType == null) providerType = Type.GetType("FreeSql.MySql.MySqlProvider`1,FreeSql.Provider.MySqlConnector")?.MakeGenericType(connType); - if (providerType == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.MySql.dll,可前往 nuget 下载"); + if (providerType == null) throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package("MySql")); break; case "SqlConnection": providerType = Type.GetType("FreeSql.SqlServer.SqlServerProvider`1,FreeSql.Provider.SqlServer")?.MakeGenericType(connType); - if (providerType == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.SqlServer.dll,可前往 nuget 下载"); + if (providerType == null) throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package("SqlServer")); break; case "NpgsqlConnection": providerType = Type.GetType("FreeSql.PostgreSQL.PostgreSQLProvider`1,FreeSql.Provider.PostgreSQL")?.MakeGenericType(connType); - if (providerType == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.PostgreSQL.dll,可前往 nuget 下载"); + if (providerType == null) throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package("PostgreSQL")); break; case "OracleConnection": providerType = Type.GetType("FreeSql.Oracle.OracleProvider`1,FreeSql.Provider.Oracle")?.MakeGenericType(connType); - if (providerType == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.Oracle.dll,可前往 nuget 下载"); + if (providerType == null) throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package("Oracle")); break; case "SQLiteConnection": providerType = Type.GetType("FreeSql.Sqlite.SqliteProvider`1,FreeSql.Provider.Sqlite")?.MakeGenericType(connType); - if (providerType == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.Sqlite.dll,可前往 nuget 下载"); + if (providerType == null) throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package("Sqlite")); break; case "DmConnection": providerType = Type.GetType("FreeSql.Dameng.DamengProvider`1,FreeSql.Provider.Dameng")?.MakeGenericType(connType); - if (providerType == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.Dameng.dll,可前往 nuget 下载"); + if (providerType == null) throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package("Dameng")); break; case "OscarConnection": providerType = Type.GetType("FreeSql.ShenTong.ShenTongProvider`1,FreeSql.Provider.ShenTong")?.MakeGenericType(connType); - if (providerType == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.ShenTong.dll,可前往 nuget 下载"); + if (providerType == null) throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package("ShenTong")); break; case "KdbndpConnection": providerType = Type.GetType("FreeSql.KingbaseES.KingbaseESProvider`1,FreeSql.Provider.KingbaseES")?.MakeGenericType(connType); - if (providerType == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.KingbaseES.dll,可前往 nuget 下载"); + if (providerType == null) throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package("KingbaseES")); break; case "FbConnection": providerType = Type.GetType("FreeSql.Firebird.FirebirdProvider`1,FreeSql.Provider.Firebird")?.MakeGenericType(connType); - if (providerType == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.Firebird.dll,可前往 nuget 下载"); + if (providerType == null) throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package("Firebird")); break; case "ClickHouseConnection": providerType = Type.GetType("FreeSql.ClickHouse.ClickHouseProvider`1,FreeSql.Provider.ClickHouse")?.MakeGenericType(connType); - if (providerType == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.ClickHouse.dll,可前往 nuget 下载"); + if (providerType == null) throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package("ClickHouse")); break; default: - throw new Exception("未实现"); + throw new Exception(CoreStrings.Not_Implemented); } lock (_dicCurdLock) { @@ -76,7 +76,7 @@ static IFreeSql GetCrud(IDbConnection dbconn) } static IFreeSql GetCrud(IDbTransaction dbtran) { - if (dbtran == null) throw new ArgumentNullException($"{nameof(dbtran)} 不能为 null"); + if (dbtran == null) throw new ArgumentNullException($"{nameof(dbtran)} {CoreStrings.Cannot_Be_NULL}"); return GetCrud(dbtran.Connection); } diff --git a/FreeSql/Extensions/FreeSqlGlobalExpressionCallExtensions.cs b/FreeSql/Extensions/FreeSqlGlobalExpressionCallExtensions.cs index 45882a225..c6cad284c 100644 --- a/FreeSql/Extensions/FreeSqlGlobalExpressionCallExtensions.cs +++ b/FreeSql/Extensions/FreeSqlGlobalExpressionCallExtensions.cs @@ -476,7 +476,7 @@ public static string StringJoinGBaseWmConcatText(object column, object delimiter if (expContext.ParsedContent["delimiter"] == "','") expContext.Result = $"wm_concat_text({expContext.ParsedContent["column"]})"; else - throw new NotImplementedException("GBase 暂时不支持逗号以外的分割符"); + throw new NotImplementedException(CoreStrings.GBase_NotSupport_OtherThanCommas); //expContext.Result = $"replace(wm_concat_text({expContext.ParsedContent["column"]}), ',', {expContext.ParsedContent["delimiter"]})"; return null; } diff --git a/FreeSql/Extensions/FreeSqlGlobalExtensions.cs b/FreeSql/Extensions/FreeSqlGlobalExtensions.cs index 0c791e846..e0ffb9c1a 100644 --- a/FreeSql/Extensions/FreeSqlGlobalExtensions.cs +++ b/FreeSql/Extensions/FreeSqlGlobalExtensions.cs @@ -157,7 +157,7 @@ internal static ConstructorInfo InternalGetTypeConstructor0OrFirst(this Type tha var ret = _dicInternalGetTypeConstructor0OrFirst.GetOrAdd(that, tp => tp.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null) ?? tp.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).OrderBy(a => a.IsPublic ? 0 : 1).FirstOrDefault()); - if (ret == null && isThrow) throw new ArgumentException($"{that.FullName} 类型无方法访问构造函数"); + if (ret == null && isThrow) throw new ArgumentException(CoreStrings.Type_Cannot_Access_Constructor(that.FullName)); return ret; } @@ -378,7 +378,7 @@ async Task> var t1sel = orm.Select() as Select1Provider; var t1expFul = t1sel.ConvertStringPropertyToExpression(property, true); var t1exp = props.Length == 1 ? t1expFul : t1sel.ConvertStringPropertyToExpression(props[0], true); - if (t1expFul == null) throw new ArgumentException($"{nameof(property)} 无法解析为表达式树"); + if (t1expFul == null) throw new ArgumentException(CoreStrings.Cannot_Resolve_ExpressionTree(nameof(property))); var propElementType = t1expFul.Type.GetGenericArguments().FirstOrDefault() ?? t1expFul.Type.GetElementType(); if (propElementType != null) //IncludeMany { @@ -394,7 +394,7 @@ async Task> return list; } var tbtr = t1tb.GetTableRef(props[0], true); - if (tbtr == null) throw new ArgumentException($"{nameof(property)} 参数错误,它不是有效的导航属性"); + if (tbtr == null) throw new ArgumentException(CoreStrings.ParameterError_NotValid_Navigation(nameof(property))); var reftb = orm.CodeFirst.GetTableByEntity(t1exp.Type); var refsel = orm.Select().AsType(t1exp.Type) as Select1Provider; if (props.Length > 1) @@ -443,14 +443,14 @@ static Select1Provider IncludeManyByPropertyNameCommonGetSelect(IFreeSql } var sel = orm.Select() as Select1Provider; var exp = sel.ConvertStringPropertyToExpression(property, true); - if (exp == null) throw new ArgumentException($"{nameof(property)} 无法解析为表达式树"); + if (exp == null) throw new ArgumentException(CoreStrings.Cannot_Resolve_ExpressionTree(nameof(property))); var memExp = exp as MemberExpression; - if (memExp == null) throw new ArgumentException($"{nameof(property)} 无法解析为表达式树2"); + if (memExp == null) throw new ArgumentException($"{CoreStrings.Cannot_Resolve_ExpressionTree(nameof(property))}2"); var parTb = orm.CodeFirst.GetTableByEntity(memExp.Expression.Type); - if (parTb == null) throw new ArgumentException($"{nameof(property)} 无法解析为表达式树3"); + if (parTb == null) throw new ArgumentException($"{CoreStrings.Cannot_Resolve_ExpressionTree(nameof(property))}3"); var propElementType = exp.Type.GetGenericArguments().FirstOrDefault() ?? exp.Type.GetElementType(); var reftb = orm.CodeFirst.GetTableByEntity(propElementType); - if (reftb == null) throw new ArgumentException($"{nameof(property)} 参数错误,它不是集合属性,必须为 IList 或者 ICollection"); + if (reftb == null) throw new ArgumentException(CoreStrings.ParameterError_NotValid_Collection(nameof(property))); if (string.IsNullOrWhiteSpace(where) == false) { @@ -463,12 +463,12 @@ static Select1Provider IncludeManyByPropertyNameCommonGetSelect(IFreeSql for (var a = 0; a < whereSplit.Length; a++) { var keyval = whereSplit[a].Split('=').Select(x => x.Trim()).Where(x => string.IsNullOrWhiteSpace(x) == false).ToArray(); - if (keyval.Length != 2) throw new ArgumentException($"{nameof(where)} 参数错误,格式 \"TopicId=Id,多组使用逗号连接\" "); + if (keyval.Length != 2) throw new ArgumentException(CoreStrings.ParameterError_NotValid_UseCommas(nameof(where))); if (reftb.ColumnsByCs.TryGetValue(keyval[0], out var keycol) == false) - throw new ArgumentException($"{nameof(where)} 参数错误,{keyval[0]} 不是有效的属性名,在实体类 {reftb.Type.DisplayCsharp()} 无法找到"); + throw new ArgumentException(CoreStrings.ParameterError_NotValid_PropertyName(nameof(where),keyval[0], reftb.Type.DisplayCsharp())); if (parTb.ColumnsByCs.TryGetValue(keyval[1], out var valcol) == false) - throw new ArgumentException($"{nameof(where)} 参数错误,{keyval[1]} 不是有效的属性名,在实体类 {parTb.Type.DisplayCsharp()} 无法找到"); + throw new ArgumentException(CoreStrings.ParameterError_NotValid_PropertyName(nameof(where), keyval[1], parTb.Type.DisplayCsharp())); var tmpExp = Expression.Equal( Expression.Convert(Expression.MakeMemberAccess(refparamExp, reftb.Properties[keyval[0]]), valcol.CsType), @@ -494,7 +494,7 @@ static Select1Provider IncludeManyByPropertyNameCommonGetSelect(IFreeSql select.Split(',').Select(x => x.Trim()).Where(x => string.IsNullOrWhiteSpace(x) == false).Select(a => { if (reftb.ColumnsByCs.TryGetValue(a, out var col) == false) - throw new ArgumentException($"{nameof(select)} 参数错误,{a} 不是有效的属性名,在实体类 {reftb.Type.DisplayCsharp()} 无法找到"); + throw new ArgumentException(CoreStrings.ParameterError_NotValid_PropertyName(nameof(select), a, reftb.Type.DisplayCsharp())); return Expression.Bind(reftb.Properties[col.CsName], Expression.MakeMemberAccess(refparamExp, reftb.Properties[col.CsName])); }).ToArray()); @@ -505,7 +505,7 @@ static Select1Provider IncludeManyByPropertyNameCommonGetSelect(IFreeSql var funcType = typeof(Func<,>).MakeGenericType(sel._tables[0].Table.Type, typeof(IEnumerable<>).MakeGenericType(reftb.Type)); var navigateSelector = Expression.Lambda(funcType, exp, sel._tables[0].Parameter); var incMethod = sel.GetType().GetMethod("IncludeMany"); - if (incMethod == null) throw new Exception("运行时错误,反射获取 IncludeMany 方法失败"); + if (incMethod == null) throw new Exception(CoreStrings.RunTimeError_Reflection_IncludeMany); incMethod.MakeGenericMethod(reftb.Type).Invoke(sel, new object[] { navigateSelector, null }); return sel; } @@ -595,7 +595,7 @@ public static ISelect AsTreeCte(this ISelect that, a.RefType == FreeSql.Internal.Model.TableRefType.OneToMany && a.RefEntityType == tb.Type).ToArray(); - if (navs.Length != 1) throw new ArgumentException($"{tb.Type.FullName} 不是父子关系,无法使用该功能"); + if (navs.Length != 1) throw new ArgumentException(CoreStrings.Entity_NotParentChild_Relationship(tb.Type.FullName)); var tbref = navs[0]; var cteName = "as_tree_cte"; @@ -641,7 +641,7 @@ public static ISelect AsTreeCte(this ISelect that, } if (int.TryParse((mysqlVersion ?? "").Split('.')[0], out var mysqlVersionFirst) && mysqlVersionFirst < 8) { - if (tbref.Columns.Count > 1) throw new ArgumentException($"{tb.Type.FullName} 是父子关系,但是 MySql 8.0 以下版本中不支持组合多主键"); + if (tbref.Columns.Count > 1) throw new ArgumentException(CoreStrings.Entity_MySQL_VersionsBelow8_NotSupport_Multiple_PrimaryKeys(tb.Type.FullName)); var mysql56Sql = ""; if (up == false) { @@ -833,7 +833,7 @@ public static TSelect OrderByRandom(this ISelect0 that case DataType.Firebird: return that.OrderBy("rand()"); } - throw new NotSupportedException($"{s0p._orm.Ado.DataType} 不支持 OrderByRandom 随机排序"); + throw new NotSupportedException($"{CoreStrings.Not_Support_OrderByRandom(s0p._orm.Ado.DataType)}"); } #endregion @@ -1033,7 +1033,7 @@ public static ColumnInfo[] GetPrimarys(TableInfo table, params string[] primarys foreach (var primary in primarys) { if (table.ColumnsByCs.TryGetValue(string.Concat(primary), out var col)) pks.Add(col); - else throw new Exception($"GetPrimarys 传递的参数 \"{primary}\" 不正确,它不属于字典数据的键名"); + else throw new Exception(CoreStrings.GetPrimarys_ParameterError_IsNotDictKey(primary)); } return pks.ToArray(); } @@ -1042,7 +1042,7 @@ public static void SetTablePrimary(TableInfo table, params string[] primarys) foreach (var primary in primarys) { if (table.ColumnsByCs.TryGetValue(string.Concat(primary), out var col)) col.Attribute.IsPrimary = true; - else throw new Exception($"GetPrimarys 传递的参数 \"{primary}\" 不正确,它不属于字典数据的键名"); + else throw new Exception(CoreStrings.GetPrimarys_ParameterError_IsNotDictKey(primary)); } table.Primarys = table.Columns.Where(a => a.Value.Attribute.IsPrimary).Select(a => a.Value).ToArray(); } diff --git a/FreeSql/FreeSql.csproj b/FreeSql/FreeSql.csproj index 2499acea5..b86d3cff0 100644 --- a/FreeSql/FreeSql.csproj +++ b/FreeSql/FreeSql.csproj @@ -20,9 +20,39 @@ false + + + + + + + + + + + + + + + + True + True + CoreStrings.Designer.tt + + + + + + TextTemplatingFileGenerator + CoreStrings.Designer.cs + + + FreeSql + + FreeSql.xml diff --git a/FreeSql/FreeSql.xml b/FreeSql/FreeSql.xml index 1702c8458..5d4268967 100644 --- a/FreeSql/FreeSql.xml +++ b/FreeSql/FreeSql.xml @@ -4584,6 +4584,647 @@ BigApple -> bigapple + + + + String resources used in FreeSql exceptions, etc. + + + These strings are exposed publicly for use by database providers and extensions. + It is unusual for application code to need these strings. + + + + + + [Table(AsTable = "{asTable}")] 特性值格式错误 + + + + + [Table(AsTable = xx)] 设置的属性名 {atmGroupsValue} 不是 DateTime 类型 + + + + + {name}: Failed to get resource {statistics} + + + + + {name}: An exception needs to be thrown + + + + + 错误的表达式格式 {column} + + + + + Chunk 功能之前不可使用 Select + + + + + 安全起见,请务必在事务开启之后,再使用 ForUpdate + + + + + 不能为 null + + + + + {name} 不能为 null + + + + + 无法匹配 {property} + + + + + {property} 无法解析为表达式树 + + + + + 参数 masterConnectionString 不可为空,请检查 UseConnectionString + + + + + 提交 + + + + + 连接失败,准备切换其他可用服务器 + + + + + 自定义表达式解析错误:类型 {exp3MethodDeclaringType} 需要定义 static ThreadLocal<ExpressionCallContext> 字段、字段、字段(重要三次提醒) + + + + + Custom { 反射信息 }不能为空,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } + + + + + Custom { 静态方法名 }不能为空,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } + + + + + Custom 对应的{{ 静态方法名 }}:{fiValueCustomArray} 未设置 [DynamicFilterCustomAttribute] 特性 + + + + + Custom 要求 Field 应该空格分割,并且长度为 2,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } + + + + + 操作的数据类型({dataDisplayCsharp}) 与 AsType({tableTypeDisplayCsharp}) 不一致,请检查。 + + + + + DateRange 要求 Value 应该逗号分割,并且长度为 2 + + + + + DateRange 要求 Value[1] 格式必须为:yyyy、yyyy-MM、yyyy-MM-dd、yyyy-MM-dd HH、yyyy、yyyy-MM-dd HH:mm + + + + + 记录可能不存在,或者【行级乐观锁】版本过旧,更新数量{sourceCount},影响的行数{affrows}。 + + + + + SlaveConnectionString 数量与 SlaveWeights 不相同 + + + + + ColumnAttribute.Name {colattrName} 重复存在,请检查(注意:不区分大小写) + + + + + 属性名 {pName} 重复存在,请检查(注意:不区分大小写) + + + + + {function} 功能要求实体类 {tableCsName} 必须有主键 + + + + + {tbTypeFullName} 是父子关系,但是 MySql 8.0 以下版本中不支持组合多主键 + + + + + {tbTypeFullName} 不是父子关系,无法使用该功能 + + + + + 这个特别的子查询不能解析 + + + + + 表达式错误,它的顶级对象不是 ParameterExpression:{exp} + + + + + 表达式错误,它不是连续的 MemberAccess 类型:{exp} + + + + + ExpressionTree 转换类型错误,值({value}),类型({valueTypeFullName}),目标类型({typeFullName}),{exMessage} + + + + + 未能解析分表字段值 {sqlWhere} + + + + + AsTable 未实现的功能 {asTable} + + + + + GBase 暂时不支持逗号以外的分割符 + + + + + tableName:{tableName} 生成了相同的分表名 + + + + + GetPrimarys 传递的参数 "{primary}" 不正确,它不属于字典数据的键名 + + + + + 已经指定了 {first},不能再指定 {second} + + + + + {tb2DbName}.{mp2MemberName} 被忽略,请检查 IsIgnore 设置,确认 get/set 为 public + + + + + Include 参数类型错误 + + + + + Include 参数类型错误,集合属性请使用 IncludeMany + + + + + Include 参数类型错误,表达式类型应该为 MemberAccess + + + + + IncludeMany 类型 {tbTypeDisplayCsharp} 的属性 {collMemMemberName} 不是有效的导航属性,提示:IsIgnore = true 不会成为导航属性 + + + + + IncludeMany {navigateSelector} 参数错误,Select 只可以使用一个参数的方法,正确格式:.Select(t =>new TNavigate {{}}) + + + + + IncludeMany {navigateSelector} 参数错误,Select lambda参数返回值必须和 {collMemElementType} 类型一致 + + + + + IncludeMany 参数1 类型错误,表达式类型应该为 MemberAccess + + + + + IncludeMany {navigateSelector} 参数类型错误,正确格式: a.collections.Take(1).Where(c =>c.aid == a.id).Select(a=> new TNavigate{{}}) + + + + + ISelect.InsertInto() 未选择属性: {displayCsharp} + + + + + ISelect.InsertInto() 类型错误: {displayCsharp} + + + + + InsertOrUpdate 功能执行 merge into 要求实体类 {CsName} 必须有主键 + + + + + InsertOrUpdate<>的泛型参数 不支持 {typeofT1},请传递您的实体类 + + + + + 【延时加载】功能需要安装 FreeSql.Extensions.LazyLoading.dll,可前往 nuget 下载 + + + + + 【延时加载】{trytbTypeName} 编译错误:{exMessage}\r\n\r\n{cscode} + + + + + 【延时加载】实体类型 {trytbTypeName} 必须声明为 public + + + + + ManyToMany 导航属性 .AsSelect() 暂时不可用于 Sum/Avg/Max/Min/First/ToOne/ToList 方法 + + + + + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 在 {tbmidCsName} 中没有找到对应的字段,如:{midTypePropsTrytbName}{findtrytbPkCsName}、{midTypePropsTrytbName}_{findtrytbPkCsName} + + + + + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {tbrefTypeName} 缺少主键标识,[Column(IsPrimary = true)] + + + + + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {tbrefTypeName} 必须存在对应的 [Navigate(ManyToMany = x)] 集合属性 + + + + + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,{tbmidCsName}.{trycolCsName} 和 {trytbCsName}.{trytbPrimarysCsName} 类型不一致 + + + + + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,中间类 {tbmidCsName}.{midTypePropsTrytbName} 错误:{exMessage} + + + + + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,中间类 {tbmidCsName}.{midTypePropsTrytbName} 导航属性不是【ManyToOne】或【OneToOne】 + + + + + 映射异常:{name} 没有一个属性名相同 + + + + + Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决 + + + + + 缺少 FreeSql 数据库实现包:FreeSql.Provider.{Provider}.dll,可前往 nuget 下载 + + + + + 缺少 FreeSql 数据库实现包:{dll},可前往 nuget 下载;如果存在 {dll} 依然报错(原因是环境问题导致反射不到类型),请在 UseConnectionString/UseConnectionFactory 第三个参数手工传入 typeof({providerType}) + + + + + 导航属性 {trytbTypeName}.{pnvName} 特性 [Navigate] Bind 数目({bindColumnsCount}) 与 外部主键数目({tbrefPrimarysLength}) 不相同 + + + + + {tb2DbName}.{mp2MemberName} 导航属性集合忘了 .AsSelect() 吗?如果在 ToList(a => a.{mp2MemberName}) 中使用,请移步参考 IncludeMany 文档。 + + + + + 【导航属性】{trytbTypeDisplayCsharp}.{pName} 缺少 set 属性 + + + + + 导航属性 {trytbTypeName}.{pnvName} 没有找到对应的字段,如:{pnvName}{findtbrefPkCsName}、{pnvName}_{findtbrefPkCsName}。或者使用 [Navigate] 特性指定关系映射。 + + + + + 导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {trytcTypeName} 缺少主键标识,[Column(IsPrimary = true)] + + + + + 导航属性 {trytbTypeName}.{pnvName} 解析错误,{trytbCsName}.{trycolCsName} 和 {tbrefCsName}.{tbrefPrimarysCsName} 类型不一致 + + + + + 导航属性 {trytbTypeName}.{pnvName} 特性 [Navigate] 解析错误,在 {tbrefTypeName} 未找到属性:{bi} + + + + + {tableTypeDisplayCsharp} 没有定义主键,无法使用 SetSource,请尝试 SetDto + + + + + 没有定义属性 + + + + + 未实现 + + + + + 未实现函数表达式 {exp} 解析 + + + + + 未实现函数表达式 {exp} 解析,参数 {expArguments} 必须为常量 + + + + + 未实现函数表达式 {exp} 解析,如果正在操作导航属性集合,请使用 .AsSelect().{exp3MethodName}({exp3ArgumentsCount}) + + + + + 未实现 MemberAccess 下的 Constant + + + + + 未实现 {name} + + + + + 不支持 + + + + + {dataType} 不支持 OrderByRandom 随机排序 + + + + + {property} 不是有效的导航属性 + + + + + {dbName} 找不到列 {memberName} + + + + + 找不到 {CsName} 对应的列 + + + + + 找不到属性:{memberName} + + + + + 找不到属性名 {proto} + + + + + Custom 找不到对应的{{ 反射信息 }}:{fiValueCustomArray} + + + + + Custom 找不到对应的{{ 静态方法名 }}:{fiValueCustomArray} + + + + + [Table(AsTable = xx)] 设置的属性名 {atmGroupsValue} 不存在 + + + + + 未指定 UseConnectionString 或者 UseConnectionFactory + + + + + 【{policyName}】ObjectPool.{GetName}() timeout {totalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081 + + + + + 【{policyName}】ObjectPool.GetAsync() The queue is too long. Policy.AsyncGetCapacity = {asyncGetCapacity} + + + + + 【OneToMany】导航属性 {trytbTypeName}.{pnvName} 在 {tbrefCsName} 中没有找到对应的字段,如:{findtrytb}{findtrytbPkCsName}、{findtrytb}_{findtrytbPkCsName} + + + + + 【OneToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,{trytbCsName}.{trytbPrimarysCsName} 和 {tbrefCsName}.{trycolCsName} 类型不一致 + + + + + 、{refpropName}{findtrytbPkCsName}、{refpropName}_{findtrytbPkCsName}。或者使用 [Navigate] 特性指定关系映射。 + + + + + 参数 field 未指定 + + + + + {property} 参数错误,它不是集合属性,必须为 IList<T> 或者 ICollection<T> + + + + + {property} 参数错误,它不是有效的导航属性 + + + + + {where} 参数错误,{keyval} 不是有效的属性名,在实体类 {reftbTypeDisplayCsharp} 无法找到 + + + + + {property} 参数错误,格式 "TopicId=Id,多组使用逗号连接" + + + + + 解析失败 {callExpMethodName} {message} + + + + + 【{policyName}】The ObjectPool has been disposed, see: https://github.com/dotnetcore/FreeSql/discussions/1079 + + + + + 【{policyName}】状态不可用,等待后台检查程序恢复方可使用。{UnavailableExceptionMessage} + + + + + 属性{trytbVersionColumnCsName} 被标注为行锁(乐观锁)(IsVersion),但其必须为数字类型 或者 byte[],并且不可为 Nullable + + + + + properties 参数不能为空 + + + + + {property} 属性名无法找到 + + + + + Range 要求 Value 应该逗号分割,并且长度为 2 + + + + + 回滚 + + + + + 运行时错误,反射获取 IncludeMany 方法失败 + + + + + {qoteSql} is NULL,除非设置特性 [Column(IsNullable = false)] + + + + + 分表字段值 "{dt}" 不能小于 "{beginTime} " + + + + + 分表字段值不能为 null + + + + + 分表字段值 "{columnValue}" 不能转化成 DateTime + + + + + 分表字段值 "{dt}" 未匹配到分表名 + + + + + T2 类型错误 + + + + + tableName 格式错误,示例:“log_{yyyyMMdd}” + + + + + {Type}.AsType 参数错误,请传入正确的实体类型 + + + + + {thatFullName} 类型无法访问构造函数 + + + + + {name} 类型错误 + + + + + {Type}.AsType 参数不支持指定为 object + + + + + 类型 {typeofFullName} 错误,不能使用 IncludeMany + + + + + 无法解析表达式:{exp} + + + + + 无法解析表达式方法 {exp3tmpCallMethodName} + + + + + 请使用 fsql.InsertDict(dict) 方法插入字典数据 + + C#: that >= between && that <= and diff --git a/FreeSql/FreeSqlBuilder.cs b/FreeSql/FreeSqlBuilder.cs index 3f51c49eb..ef5feba63 100644 --- a/FreeSql/FreeSqlBuilder.cs +++ b/FreeSql/FreeSqlBuilder.cs @@ -39,7 +39,7 @@ public partial class FreeSqlBuilder /// public FreeSqlBuilder UseConnectionString(DataType dataType, string connectionString, Type providerType = null) { - if (_connectionFactory != null) throw new Exception("已经指定了 UseConnectionFactory,不能再指定 UseConnectionString"); + if (_connectionFactory != null) throw new Exception(CoreStrings.Has_Specified_Cannot_Specified_Second("UseConnectionFactory", "UseConnectionString")); _dataType = dataType; _masterConnectionString = connectionString; _providerType = providerType; @@ -52,13 +52,13 @@ public FreeSqlBuilder UseConnectionString(DataType dataType, string connectionSt /// public FreeSqlBuilder UseSlave(params string[] slaveConnectionString) { - if (_connectionFactory != null) throw new Exception("已经指定了 UseConnectionFactory,不能再指定 UseSlave"); + if (_connectionFactory != null) throw new Exception(CoreStrings.Has_Specified_Cannot_Specified_Second("UseConnectionFactory", "UseSlave")); _slaveConnectionString = slaveConnectionString; return this; } public FreeSqlBuilder UseSlaveWeight(params int[] slaveWeights) { - if (_slaveConnectionString?.Length != slaveWeights.Length) throw new Exception("SlaveConnectionString 数量与 SlaveWeights 不相同"); + if (_slaveConnectionString?.Length != slaveWeights.Length) throw new Exception(CoreStrings.Different_Number_SlaveConnectionString_SlaveWeights); _slaveWeights = slaveWeights; return this; } @@ -71,8 +71,8 @@ public FreeSqlBuilder UseSlaveWeight(params int[] slaveWeights) /// public FreeSqlBuilder UseConnectionFactory(DataType dataType, Func connectionFactory, Type providerType = null) { - if (string.IsNullOrEmpty(_masterConnectionString) == false) throw new Exception("已经指定了 UseConnectionString,不能再指定 UseConnectionFactory"); - if (_slaveConnectionString?.Any() == true) throw new Exception("已经指定了 UseSlave,不能再指定 UseConnectionFactory"); + if (string.IsNullOrEmpty(_masterConnectionString) == false) throw new Exception(CoreStrings.Has_Specified_Cannot_Specified_Second("UseConnectionString", "UseConnectionFactory")); + if (_slaveConnectionString?.Any() == true) throw new Exception(CoreStrings.Has_Specified_Cannot_Specified_Second("UseSlave", "UseConnectionFactory")); _dataType = dataType; _connectionFactory = connectionFactory; _providerType = providerType; @@ -175,7 +175,7 @@ public FreeSqlBuilder UseExitAutoDisposePool(bool value) public IFreeSql Build() => Build(); public IFreeSql Build() { - if (string.IsNullOrEmpty(_masterConnectionString) && _connectionFactory == null) throw new Exception("参数 masterConnectionString 不可为空,请检查 UseConnectionString"); + if (string.IsNullOrEmpty(_masterConnectionString) && _connectionFactory == null) throw new Exception(CoreStrings.Check_UseConnectionString); IFreeSql ret = null; var type = _providerType; if (type != null) @@ -185,7 +185,7 @@ public IFreeSql Build() } else { - Action throwNotFind = (dll, providerType) => throw new Exception($"缺少 FreeSql 数据库实现包:{dll},可前往 nuget 下载;如果存在 {dll} 依然报错(原因是环境问题导致反射不到类型),请在 UseConnectionString/UseConnectionFactory 第三个参数手工传入 typeof({providerType})"); + Action throwNotFind = (dll, providerType) => throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package_Reason(dll, providerType)); switch (_dataType) { case DataType.MySql: @@ -283,7 +283,7 @@ public IFreeSql Build() if (type == null) throwNotFind("FreeSql.Provider.GBase.dll", "FreeSql.GBase.GBaseProvider<>"); break; - default: throw new Exception("未指定 UseConnectionString 或者 UseConnectionFactory"); + default: throw new Exception(CoreStrings.NotSpecified_UseConnectionString_UseConnectionFactory); } } ret = Activator.CreateInstance(type, new object[] { _masterConnectionString, _slaveConnectionString, _connectionFactory }) as IFreeSql; diff --git a/FreeSql/Internal/CommonExpression.cs b/FreeSql/Internal/CommonExpression.cs index 05616d720..bac132d44 100644 --- a/FreeSql/Internal/CommonExpression.cs +++ b/FreeSql/Internal/CommonExpression.cs @@ -135,7 +135,8 @@ public bool ReadAnonymousField(List _tables, StringBuilder fiel if (index >= 0) field.Append(_common.FieldAsAlias($"as{++index}")); parent.Childs.Add(child); } - if (_tables.Count > 1) { //如果下级导航属性被 Include 过,则将他们也查询出来 + if (_tables.Count > 1) + { //如果下级导航属性被 Include 过,则将他们也查询出来 foreach (var memProp in tb.Properties.Values) { var memtbref = tb.GetTableRef(memProp.Name, false); @@ -162,8 +163,8 @@ public bool ReadAnonymousField(List _tables, StringBuilder fiel } else { - if (select != null && findIncludeMany != null && select._includeToList.Any() && exp.Type.IsGenericType && - typeof(IEnumerable).IsAssignableFrom(exp.Type) && + if (select != null && findIncludeMany != null && select._includeToList.Any() && exp.Type.IsGenericType && + typeof(IEnumerable).IsAssignableFrom(exp.Type) && typeof(ICollection<>).MakeGenericType(exp.Type.GetGenericArguments().FirstOrDefault()).IsAssignableFrom(exp.Type)) { var includeKey = ""; @@ -285,7 +286,7 @@ public bool ReadAnonymousField(List _tables, StringBuilder fiel ReadAnonymousField(_tables, field, child, ref index, initAssignExp.Expression, select, diymemexp, whereGlobalFilter, findIncludeMany, false); } } - if (parent.Childs.Any() == false) throw new Exception($"映射异常:{initExp.NewExpression.Type.Name} 没有一个属性名相同"); + if (parent.Childs.Any() == false) throw new Exception(CoreStrings.Mapping_Exception_HasNo_SamePropertyName(initExp.NewExpression.Type.Name)); return true; case ExpressionType.New: var newExp = exp as NewExpression; @@ -350,7 +351,7 @@ public bool ReadAnonymousField(List _tables, StringBuilder fiel } } } - if (parent.Childs.Any() == false) throw new Exception($"映射异常:{newExp.Type.Name} 没有一个属性名相同"); + if (parent.Childs.Any() == false) throw new Exception(CoreStrings.Mapping_Exception_HasNo_SamePropertyName(newExp.Type.Name)); return true; } parent.DbField = $"({ExpressionLambdaToSql(exp, getTSC())})"; @@ -367,13 +368,13 @@ public object ReadAnonymous(ReadAnonymousTypeInfo parent, DbDataReader dr, ref i if (notRead) { ++index; - if (parent.Property != null) + if (parent.Property != null) return Utils.GetDataReaderValue(parent.Property.PropertyType, null); return Utils.GetDataReaderValue(parent.CsType, null); } object objval = Utils.InternalDataReaderGetValue(_common, dr, ++index); // dr.GetValue(++index); if (dbValue != null) dbValue.DbValue = objval == DBNull.Value ? null : objval; - if (parent.CsType != parent.MapType) + if (parent.CsType != parent.MapType) objval = Utils.GetDataReaderValue(parent.MapType, objval); objval = Utils.GetDataReaderValue(parent.CsType, objval); if (parent.Property != null && parent.CsType != parent.Property.PropertyType) @@ -468,7 +469,7 @@ public string[] ExpressionSelectColumns_MemberAccess_New_NewArrayInit(List(); foreach (var newArrExp in newArr.Expressions) newArrMembers.AddRange(ExpressionSelectColumns_MemberAccess_New_NewArrayInit(_tables, newArrExp, isQuoteName, diymemexp)); return newArrMembers.Distinct().Select(a => a.Trim('\'')).ToArray(); - default: throw new ArgumentException($"无法解析表达式:{exp}"); + default: throw new ArgumentException(CoreStrings.Unable_Parse_Expression(exp)); } return new string[0]; } @@ -623,9 +624,9 @@ rightExp is UnaryExpression rightExpUexp && ColumnInfo rightMapColumn = null; var isRightMapType = false; if (isLeftMapType) oldMapType = tsc.SetMapTypeReturnOld(leftMapColumn.Attribute.MapType); - + var right = ExpressionLambdaToSql(rightExp, tsc); - if (right != "NULL" && isLeftMapType && + if (right != "NULL" && isLeftMapType && //判断参数化后的bug !(right.Contains('@') || right.Contains('?') || right.Contains(':')) && //三元表达式后,取消此条件 #184 @@ -787,12 +788,13 @@ public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) exp3.Method.GetCustomAttributes(typeof(ExpressionCallAttribute), true).Any() )) { - var ecc = new ExpressionCallContext { - _commonExp = this, - _tsc = tsc, - DataType = _ado.DataType, - UserParameters = tsc.dbParams == null ? null : new List(), - FormatSql = obj => formatSql(obj, null, null, null) + var ecc = new ExpressionCallContext + { + _commonExp = this, + _tsc = tsc, + DataType = _ado.DataType, + UserParameters = tsc.dbParams == null ? null : new List(), + FormatSql = obj => formatSql(obj, null, null, null) }; var exp3MethodParams = exp3.Method.GetParameters(); var dbParamsIndex = tsc.dbParams?.Count; @@ -852,10 +854,10 @@ public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) else exp3InvokeParams[a] = ecc; } - var eccFields = _dicTypeExpressionCallClassContextFields.GetOrAdd(exp3.Method.DeclaringType, dttp => + var eccFields = _dicTypeExpressionCallClassContextFields.GetOrAdd(exp3.Method.DeclaringType, dttp => dttp.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Static).Where(a => a.FieldType == typeof(ThreadLocal)).ToArray()); if (eccFields.Any() == false) - throw new Exception($"自定义表达式解析错误:类型 {exp3.Method.DeclaringType} 需要定义 static ThreadLocal 字段、字段、字段(重要三次提醒)"); + throw new Exception(CoreStrings.Custom_Expression_ParsingError(exp3.Method.DeclaringType)); foreach (var eccField in eccFields) typeof(ThreadLocal).GetProperty("Value").SetValue(eccField.GetValue(null), ecc, null); try @@ -999,7 +1001,7 @@ public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) fsql = Expression.Lambda(exp3tmpTestCall).Compile().DynamicInvoke(); var fsqlFindMethod = fsql.GetType().GetMethod(exp3tmpCall.Method.Name, exp3tmpCall.Arguments.Select(a => a.Type).ToArray()); if (fsqlFindMethod == null) - throw new Exception($"无法解析表达式方法 {exp3tmpCall.Method.Name}"); + throw new Exception(CoreStrings.Unable_Parse_ExpressionMethod(exp3tmpCall.Method.Name)); var exp3StackOld = exp3Stack; exp3Stack = new Stack(); exp3Stack.Push(Expression.Call(Expression.Constant(fsql), fsqlFindMethod, exp3tmpCall.Arguments)); @@ -1010,7 +1012,8 @@ public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) fsqlType = fsql?.GetType(); if (fsqlType == null) break; var fsqlSelect0 = fsql as Select0Provider; - switch (exp3.Method.Name) { + switch (exp3.Method.Name) + { case "Any": //exists switch (_ado.DataType) { @@ -1035,7 +1038,7 @@ public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) //fsqltables[0].Alias = $"{tsc._tables[0].Alias}_{fsqltables[0].Alias}"; if (fsqltables != tsc._tables) { - if (tsc._tables == null && tsc.diymemexp == null) throw new NotSupportedException($"这个特别的子查询不能解析"); //2020-12-11 IUpdate 条件不支持子查询 + if (tsc._tables == null && tsc.diymemexp == null) throw new NotSupportedException(CoreStrings.EspeciallySubquery_Cannot_Parsing); //2020-12-11 IUpdate 条件不支持子查询 if (tsc._tables != null) //groupby is null { fsqltables.AddRange(tsc._tables.Select(a => new SelectTableInfo @@ -1230,7 +1233,7 @@ public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) var exp3Args0 = (exp3.Arguments[0] as UnaryExpression)?.Operand as LambdaExpression; manySubSelectAggMethod = _dicSelectMethodToSql.GetOrAdd(fsqlType, fsqlType2 => fsqlType2.GetMethods().Where(a => a.Name == "ToSql" && a.GetParameters().Length == 2 && a.GetParameters()[1].ParameterType == typeof(FieldAliasOptions) && a.GetGenericArguments().Length == 1).FirstOrDefault()); - if (manySubSelectAggMethod == null || exp3Args0 == null) throw new ArgumentException($"ManyToMany 导航属性 .AsSelect() 暂时不可用于 Sum/Avg/Max/Min/First/ToOne/ToList 方法"); + if (manySubSelectAggMethod == null || exp3Args0 == null) throw new ArgumentException(CoreStrings.ManyToMany_AsSelect_NotSupport_Sum_Avg_etc); manySubSelectAggMethod = manySubSelectAggMethod.MakeGenericMethod(exp3Args0.ReturnType); var fsqls0p = fsql as Select0Provider; var fsqls0pWhere = fsqls0p._where.ToString(); @@ -1358,8 +1361,8 @@ public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) other3Exp = ExpressionLambdaToSqlOther(exp3, tsc); if (string.IsNullOrEmpty(other3Exp) == false) return other3Exp; if (exp3.IsParameter() == false) return formatSql(Expression.Lambda(exp3).Compile().DynamicInvoke(), tsc.mapType, tsc.mapColumnTmp, tsc.dbParams); - if (exp3.Method.DeclaringType == typeof(Enumerable)) throw new Exception($"未实现函数表达式 {exp3} 解析。如果正在操作导航属性集合,请使用 .AsSelect().{exp3.Method.Name}({(exp3.Arguments.Count > 1 ? "..." : "")})"); - throw new Exception($"未实现函数表达式 {exp3} 解析"); + if (exp3.Method.DeclaringType == typeof(Enumerable)) throw new Exception(CoreStrings.Not_Implemented_Expression_UseAsSelect(exp3, exp3.Method.Name, (exp3.Arguments.Count > 1 ? "..." : ""))); + throw new Exception(CoreStrings.Not_Implemented_Expression(exp3)); case ExpressionType.Parameter: case ExpressionType.MemberAccess: var exp4 = exp as MemberExpression; @@ -1434,7 +1437,7 @@ public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) break; case ExpressionType.MemberAccess: var expStackFirstMem = expStack.First() as MemberExpression; - if (expStackFirstMem.Expression?.NodeType == ExpressionType.Constant) + if (expStackFirstMem.Expression?.NodeType == ExpressionType.Constant) firstValue = (expStackFirstMem.Expression as ConstantExpression)?.Value; else return formatSql(Expression.Lambda(exp).Compile().DynamicInvoke(), tsc.mapType, tsc.mapColumnTmp, tsc.dbParams); @@ -1479,8 +1482,8 @@ public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) if (tb.ColumnsByCs.ContainsKey(memberExp.Member.Name) == false) { if (tb.ColumnsByCsIgnore.ContainsKey(memberExp.Member.Name)) - throw new ArgumentException($"{tb.DbName}.{memberExp.Member.Name} 被忽略,请检查 IsIgnore 设置,确认 get/set 为 public"); - throw new ArgumentException($"{tb.DbName} 找不到列 {memberExp.Member.Name}"); + throw new ArgumentException(CoreStrings.Ignored_Check_Confirm_PublicGetSet(tb.DbName, memberExp.Member.Name)); + throw new ArgumentException(CoreStrings.NotFound_Column(tb.DbName, memberExp.Member.Name)); } var curcol = tb.ColumnsByCs[memberExp.Member.Name]; if (tsc._selectColumnMap != null) @@ -1497,7 +1500,7 @@ public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) if (tsc.style == ExpressionStyle.SelectColumns) { finds = tsc._tables.Where(a => a.Table.Type == tbtmp.Type && a.Alias == alias).ToArray(); - if (finds.Any() == false && alias.Contains("__") == false) + if (finds.Any() == false && alias.Contains("__") == false) finds = tsc._tables.Where(a => a.Table.Type == tbtmp.Type).ToArray(); if (finds.Any()) finds = new[] { finds.First() }; } @@ -1595,7 +1598,7 @@ public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) switch (exp2.NodeType) { case ExpressionType.Constant: - throw new NotImplementedException("未实现 MemberAccess 下的 Constant"); + throw new NotImplementedException($"{CoreStrings.Not_Implemented_MemberAcess_Constant}"); case ExpressionType.Parameter: case ExpressionType.MemberAccess: @@ -1666,10 +1669,10 @@ public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) } } if (tb2.ColumnsByCsIgnore.ContainsKey(mp2.Member.Name)) - throw new ArgumentException($"{tb2.DbName}.{mp2.Member.Name} 被忽略,请检查 IsIgnore 设置,确认 get/set 为 public"); + throw new ArgumentException(CoreStrings.Ignored_Check_Confirm_PublicGetSet(tb2.DbName, mp2.Member.Name)); if (tb2.GetTableRef(mp2.Member.Name, false) != null) - throw new ArgumentException($"{tb2.DbName}.{mp2.Member.Name} 导航属性集合忘了 .AsSelect() 吗?如果在 ToList(a => a.{mp2.Member.Name}) 中使用,请移步参考 IncludeMany 文档。"); - throw new ArgumentException($"{tb2.DbName} 找不到列 {mp2.Member.Name}"); + throw new ArgumentException(CoreStrings.Navigation_Missing_AsSelect(tb2.DbName, mp2.Member.Name)); + throw new ArgumentException(CoreStrings.NotFound_Column(tb2.DbName, mp2.Member.Name)); } col2 = tb2.ColumnsByCs[mp2.Member.Name]; if (tsc._selectColumnMap != null && find2 != null) @@ -1834,9 +1837,19 @@ public string GetWhereCascadeSql(SelectTableInfo tb, List fil new ReplaceParameterVisitor().Modify(fl.Where, newParameter), newParameter ); - var whereSql = ExpressionLambdaToSql(expExp.Body, new ExpTSC { _tables = - isMultitb ? new List(new[] { tb }) : null, - _selectColumnMap = null, diymemexp = null, tbtype = SelectTableInfoType.From, isQuoteName = true, isDisableDiyParse = false, style = ExpressionStyle.Where, currentTable = tb.Table, alias001 = tb.Alias }); + var whereSql = ExpressionLambdaToSql(expExp.Body, new ExpTSC + { + _tables = + isMultitb ? new List(new[] { tb }) : null, + _selectColumnMap = null, + diymemexp = null, + tbtype = SelectTableInfoType.From, + isQuoteName = true, + isDisableDiyParse = false, + style = ExpressionStyle.Where, + currentTable = tb.Table, + alias001 = tb.Alias + }); whereSql = GetBoolString(expExp.Body, whereSql); if (isEmpty == false) sb.Append(" AND "); @@ -2121,7 +2134,7 @@ void LocalInitSelectProvider() e.Result = $"({select.ToSql().Replace(" \r\n", " \r\n ")})"; return; } - throw throwCallExp(" 不支持"); + throw throwCallExp(CoreStrings.Not_Support); case "ToList": if (callExp.Arguments.Count == 1) { @@ -2130,7 +2143,7 @@ void LocalInitSelectProvider() e.Result = $"({select.ToSql().Replace(" \r\n", " \r\n ")})"; return; } - throw throwCallExp(" 不支持"); + throw throwCallExp(CoreStrings.Not_Support); case "Contains": if (callExp.Arguments.Count == 2) { @@ -2148,7 +2161,7 @@ void LocalInitSelectProvider() select.Distinct(); break; } - throw throwCallExp(" 不支持"); + throw throwCallExp(CoreStrings.Not_Support); case "OrderBy": select._tables[0].Parameter = (callExp.Arguments[1] as LambdaExpression)?.Parameters.FirstOrDefault(); LocalSetSelectProviderAlias(select._tables[0].Parameter.Name); @@ -2179,7 +2192,7 @@ void LocalInitSelectProvider() select.InternalWhere(whereParam); break; } - throw throwCallExp(" 不支持"); + throw throwCallExp(CoreStrings.Not_Support); case "Skip": select.Offset((int)callExp.Arguments[1].GetConstExprValue()); @@ -2197,9 +2210,9 @@ void LocalInitSelectProvider() select._selectExpression = selectParam; break; } - throw throwCallExp(" 不支持"); + throw throwCallExp(CoreStrings.Not_Support); } - Exception throwCallExp(string message) => new Exception($"解析失败 {callExp.Method.Name} {message}"); + Exception throwCallExp(string message) => new Exception(CoreStrings.Parsing_Failed(callExp.Method.Name,message)); } } } diff --git a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProvider.cs b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProvider.cs index 0c82881c1..ae30c2fe4 100644 --- a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProvider.cs +++ b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProvider.cs @@ -2,7 +2,6 @@ using FreeSql.Internal.ObjectPool; using System; using System.Collections; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Data.Common; @@ -631,7 +630,7 @@ public void ExecuteReaderMultiple(int multipleResult, DbConnection connection, D ReturnConnection(pool, conn, ex); //pool.Return(conn, ex); if (IsTracePerformance) logtxt.Append("Pool.Return: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); } - LoggerException(pool, pc, new Exception($"连接失败,准备切换其他可用服务器"), dt, logtxt, false); + LoggerException(pool, pc, new Exception(CoreStrings.Connection_Failed_Switch_Servers), dt, logtxt, false); pc.cmd.Parameters.Clear(); if (DataType == DataType.Sqlite) pc.cmd.Dispose(); ExecuteReaderMultiple(multipleResult, connection, transaction, fetchHandler, schemaHandler, cmdType, cmdText, cmdTimeout, cmdParms); diff --git a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderAsync.cs b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderAsync.cs index 52f88e687..23a12c2f5 100644 --- a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderAsync.cs +++ b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderAsync.cs @@ -537,7 +537,7 @@ async public Task ExecuteReaderMultipleAsync(int multipleResult, DbConnection co ReturnConnection(pool, conn, ex); //pool.Return(conn, ex); if (IsTracePerformance) logtxt.Append("Pool.Return: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); } - LoggerException(pool, pc, new Exception($"连接失败,准备切换其他可用服务器"), dt, logtxt, false); + LoggerException(pool, pc, new Exception(CoreStrings.Connection_Failed_Switch_Servers), dt, logtxt, false); pc.cmd.Parameters.Clear(); if (DataType == DataType.Sqlite) pc.cmd.Dispose(); await ExecuteReaderMultipleAsync(multipleResult, connection, transaction, fetchHandler, schemaHandler, cmdType, cmdText, cmdTimeout, cmdParms, cancellationToken); diff --git a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderTransaction.cs b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderTransaction.cs index a936f7670..f0e49e747 100644 --- a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderTransaction.cs +++ b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderTransaction.cs @@ -78,7 +78,7 @@ private void CommitTransaction(bool isCommit, Transaction2 tran, Exception rollb _trans.TryRemove(tran.Connection.LastGetThreadId, out var oldtran); Exception ex = null; - if (string.IsNullOrEmpty(remark)) remark = isCommit ? "提交" : "回滚"; + if (string.IsNullOrEmpty(remark)) remark = isCommit ? CoreStrings.Commit : CoreStrings.RollBack; try { if (tran.Transaction.Connection != null) //用户自行 Commit、Rollback diff --git a/FreeSql/Internal/CommonProvider/BaseDbProvider.cs b/FreeSql/Internal/CommonProvider/BaseDbProvider.cs index 96528c440..f7e77bc20 100644 --- a/FreeSql/Internal/CommonProvider/BaseDbProvider.cs +++ b/FreeSql/Internal/CommonProvider/BaseDbProvider.cs @@ -18,23 +18,23 @@ public abstract partial class BaseDbProvider : IFreeSql public IInsert Insert() where T1 : class => CreateInsertProvider(); public IInsert Insert(T1 source) where T1 : class { - if (typeof(T1) == typeof(Dictionary)) throw new Exception("请使用 fsql.InsertDict(dict) 方法插入字典数据"); + if (typeof(T1) == typeof(Dictionary)) throw new Exception(CoreStrings.Use_InsertDict_Method); return this.Insert().AppendData(source); } public IInsert Insert(T1[] source) where T1 : class { - if (typeof(T1) == typeof(Dictionary)) throw new Exception("请使用 fsql.InsertDict(dict) 方法插入字典数据"); + if (typeof(T1) == typeof(Dictionary)) throw new Exception(CoreStrings.Use_InsertDict_Method); return this.Insert().AppendData(source); } public IInsert Insert(List source) where T1 : class { - if (typeof(T1) == typeof(Dictionary)) throw new Exception("请使用 fsql.InsertDict(dict) 方法插入字典数据"); + if (typeof(T1) == typeof(Dictionary)) throw new Exception(CoreStrings.Use_InsertDict_Method); return this.Insert().AppendData(source); } public IInsert Insert(IEnumerable source) where T1 : class { - if (typeof(T1) == typeof(Dictionary)) throw new Exception("请使用 fsql.InsertDict(dict) 方法插入字典数据"); + if (typeof(T1) == typeof(Dictionary)) throw new Exception(CoreStrings.Use_InsertDict_Method); return this.Insert().AppendData(source); } public IUpdate Update() where T1 : class => CreateUpdateProvider(null); diff --git a/FreeSql/Internal/CommonProvider/DeleteProvider.cs b/FreeSql/Internal/CommonProvider/DeleteProvider.cs index 0fe798c0e..21f814da4 100644 --- a/FreeSql/Internal/CommonProvider/DeleteProvider.cs +++ b/FreeSql/Internal/CommonProvider/DeleteProvider.cs @@ -160,10 +160,10 @@ public IDelete AsTable(string tableName) } public IDelete AsType(Type entityType) { - if (entityType == typeof(object)) throw new Exception("IDelete.AsType 参数不支持指定为 object"); + if (entityType == typeof(object)) throw new Exception(CoreStrings.TypeAsType_NotSupport_Object("IDelete")); if (entityType == _table.Type) return this; var newtb = _commonUtils.GetTableByEntity(entityType); - _table = newtb ?? throw new Exception("IDelete.AsType 参数错误,请传入正确的实体类型"); + _table = newtb ?? throw new Exception(CoreStrings.Type_AsType_Parameter_Error("IDelete")); if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); return this; } diff --git a/FreeSql/Internal/CommonProvider/InsertOrUpdateProvider.cs b/FreeSql/Internal/CommonProvider/InsertOrUpdateProvider.cs index 3e6b4a97f..436bfff61 100644 --- a/FreeSql/Internal/CommonProvider/InsertOrUpdateProvider.cs +++ b/FreeSql/Internal/CommonProvider/InsertOrUpdateProvider.cs @@ -38,7 +38,7 @@ public InsertOrUpdateProvider(IFreeSql orm, CommonUtils commonUtils, CommonExpre _commonExpression = commonExpression; _table = _commonUtils.GetTableByEntity(typeof(T1)); if (_table == null && typeof(T1) != typeof(Dictionary)) - throw new Exception($"InsertOrUpdate<>的泛型参数 不支持 {typeof(T1)},请传递您的实体类"); + throw new Exception(CoreStrings.InsertOrUpdate_NotSuport_Generic_UseEntity(typeof(T1))); if (_orm.CodeFirst.IsAutoSyncStructure && typeof(T1) != typeof(object)) _orm.CodeFirst.SyncStructure(); IdentityColumn = _table?.Primarys.Where(a => a.Attribute.IsIdentity).FirstOrDefault(); } @@ -88,7 +88,7 @@ public static void AuditDataValue(object sender, T1 data, IFreeSql orm, TableInf { if (data == null || table == null) return; if (typeof(T1) == typeof(object) && new[] { table.Type, table.TypeLazy }.Contains(data.GetType()) == false) - throw new Exception($"操作的数据类型({data.GetType().DisplayCsharp()}) 与 AsType({table.Type.DisplayCsharp()}) 不一致,请检查。"); + throw new Exception(CoreStrings.DataType_AsType_Inconsistent(data.GetType().DisplayCsharp(), table.Type.DisplayCsharp())); if (orm.Aop.AuditValueHandler == null) return; foreach (var col in table.Columns.Values) { @@ -157,10 +157,10 @@ public IInsertOrUpdate AsTable(string tableName) } public IInsertOrUpdate AsType(Type entityType) { - if (entityType == typeof(object)) throw new Exception("IInsertOrUpdate.AsType 参数不支持指定为 object"); + if (entityType == typeof(object)) throw new Exception(CoreStrings.TypeAsType_NotSupport_Object("IInsertOrUpdate")); if (entityType == _table.Type) return this; var newtb = _commonUtils.GetTableByEntity(entityType); - _table = newtb ?? throw new Exception("IInsertOrUpdate.AsType 参数错误,请传入正确的实体类型"); + _table = newtb ?? throw new Exception(CoreStrings.Type_AsType_Parameter_Error("IInsertOrUpdate")); if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); IdentityColumn = _table.Primarys.Where(a => a.Attribute.IsIdentity).FirstOrDefault(); return this; @@ -267,7 +267,7 @@ public int ExecuteAffrows() _SplitSourceByIdentityValueIsNullFlag = 1; foreach (var tmpsource in ss.Item1) { - _source = tmpsource; + _source = tmpsource; affrows += this.RawExecuteAffrows(); } _SplitSourceByIdentityValueIsNullFlag = 2; @@ -299,12 +299,12 @@ public int ExecuteAffrows() affrows += this.RawExecuteAffrows(); } _transaction.Commit(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "提交", null)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.Commit, null)); } catch (Exception ex) { _transaction.Rollback(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "回滚", ex)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.RollBack, ex)); throw; } _transaction = null; @@ -417,12 +417,12 @@ async public Task ExecuteAffrowsAsync(CancellationToken cancellationToken = affrows += await this.RawExecuteAffrowsAsync(cancellationToken); } _transaction.Commit(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "提交", null)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.Commit, null)); } catch (Exception ex) { _transaction.Rollback(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "回滚", ex)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.RollBack, ex)); throw; } _transaction = null; diff --git a/FreeSql/Internal/CommonProvider/InsertProvider.cs b/FreeSql/Internal/CommonProvider/InsertProvider.cs index fb2e67ea3..4fa5a1978 100644 --- a/FreeSql/Internal/CommonProvider/InsertProvider.cs +++ b/FreeSql/Internal/CommonProvider/InsertProvider.cs @@ -161,7 +161,7 @@ public static void AuditDataValue(object sender, T1 data, IFreeSql orm, TableInf { if (data == null || table == null) return; if (typeof(T1) == typeof(object) && new[] { table.Type, table.TypeLazy }.Contains(data.GetType()) == false) - throw new Exception($"操作的数据类型({data.GetType().DisplayCsharp()}) 与 AsType({table.Type.DisplayCsharp()}) 不一致,请检查。"); + throw new Exception(CoreStrings.DataType_AsType_Inconsistent(data.GetType().DisplayCsharp(), table.Type.DisplayCsharp())); foreach (var col in table.Columns.Values) { object val = col.GetValue(data); @@ -281,7 +281,7 @@ protected virtual int SplitExecuteAffrows(int valuesLimit, int parameterLimit) } else { - if (_orm.Ado.MasterPool == null) throw new Exception("Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决"); + if (_orm.Ado.MasterPool == null) throw new Exception(CoreStrings.MasterPool_IsNull_UseTransaction); using (var conn = _orm.Ado.MasterPool.Get()) { _transaction = conn.Value.BeginTransaction(); @@ -296,12 +296,12 @@ protected virtual int SplitExecuteAffrows(int valuesLimit, int parameterLimit) ret += this.RawExecuteAffrows(); } _transaction.Commit(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "提交", null)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.Commit, null)); } catch (Exception ex) { _transaction.Rollback(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "回滚", ex)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.RollBack, ex)); throw; } _transaction = null; @@ -361,7 +361,7 @@ protected long SplitExecuteIdentity(int valuesLimit, int parameterLimit) } else { - if (_orm.Ado.MasterPool == null) throw new Exception("Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决"); + if (_orm.Ado.MasterPool == null) throw new Exception(CoreStrings.MasterPool_IsNull_UseTransaction); using (var conn = _orm.Ado.MasterPool.Get()) { _transaction = conn.Value.BeginTransaction(); @@ -377,12 +377,12 @@ protected long SplitExecuteIdentity(int valuesLimit, int parameterLimit) else ret = this.RawExecuteIdentity(); } _transaction.Commit(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "提交", null)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.Commit, null)); } catch (Exception ex) { _transaction.Rollback(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "回滚", ex)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.RollBack, ex)); throw; } _transaction = null; @@ -441,7 +441,7 @@ protected List SplitExecuteInserted(int valuesLimit, int parameterLimit) } else { - if (_orm.Ado.MasterPool == null) throw new Exception("Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决"); + if (_orm.Ado.MasterPool == null) throw new Exception(CoreStrings.MasterPool_IsNull_UseTransaction); using (var conn = _orm.Ado.MasterPool.Get()) { _transaction = conn.Value.BeginTransaction(); @@ -456,12 +456,12 @@ protected List SplitExecuteInserted(int valuesLimit, int parameterLimit) ret.AddRange(this.RawExecuteInserted()); } _transaction.Commit(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "提交", null)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.Commit, null)); } catch (Exception ex) { _transaction.Rollback(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "回滚", ex)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.RollBack, ex)); throw; } _transaction = null; @@ -571,11 +571,11 @@ public IInsert AsTable(string tableName) } public IInsert AsType(Type entityType) { - if (entityType == typeof(object)) throw new Exception("IInsert.AsType 参数不支持指定为 object"); + if (entityType == typeof(object)) throw new Exception(CoreStrings.TypeAsType_NotSupport_Object("IInsert")); if (entityType == typeof(T1)) return this; if (entityType == _table.Type) return this; var newtb = _commonUtils.GetTableByEntity(entityType); - _table = newtb ?? throw new Exception("IInsert.AsType 参数错误,请传入正确的实体类型"); + _table = newtb ?? throw new Exception(CoreStrings.Type_AsType_Parameter_Error("IInsert")); if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); IgnoreCanInsert(); return this; diff --git a/FreeSql/Internal/CommonProvider/InsertProviderAsync.cs b/FreeSql/Internal/CommonProvider/InsertProviderAsync.cs index 1dfefd6b4..54b94b275 100644 --- a/FreeSql/Internal/CommonProvider/InsertProviderAsync.cs +++ b/FreeSql/Internal/CommonProvider/InsertProviderAsync.cs @@ -55,7 +55,7 @@ async protected virtual Task SplitExecuteAffrowsAsync(int valuesLimit, int } else { - if (_orm.Ado.MasterPool == null) throw new Exception("Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决"); + if (_orm.Ado.MasterPool == null) throw new Exception(CoreStrings.MasterPool_IsNull_UseTransaction); using (var conn = await _orm.Ado.MasterPool.GetAsync()) { _transaction = conn.Value.BeginTransaction(); @@ -70,12 +70,12 @@ async protected virtual Task SplitExecuteAffrowsAsync(int valuesLimit, int ret += await this.RawExecuteAffrowsAsync(cancellationToken); } _transaction.Commit(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "提交", null)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.Commit, null)); } catch (Exception ex) { _transaction.Rollback(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "回滚", ex)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.RollBack, ex)); throw; } _transaction = null; @@ -135,7 +135,7 @@ async protected virtual Task SplitExecuteIdentityAsync(int valuesLimit, in } else { - if (_orm.Ado.MasterPool == null) throw new Exception("Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决"); + if (_orm.Ado.MasterPool == null) throw new Exception(CoreStrings.MasterPool_IsNull_UseTransaction); using (var conn = await _orm.Ado.MasterPool.GetAsync()) { _transaction = conn.Value.BeginTransaction(); @@ -151,12 +151,12 @@ async protected virtual Task SplitExecuteIdentityAsync(int valuesLimit, in else ret = await this.RawExecuteIdentityAsync(cancellationToken); } _transaction.Commit(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "提交", null)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.Commit, null)); } catch (Exception ex) { _transaction.Rollback(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "回滚", ex)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.RollBack, ex)); throw; } _transaction = null; @@ -215,7 +215,7 @@ async protected virtual Task> SplitExecuteInsertedAsync(int valuesLimit } else { - if (_orm.Ado.MasterPool == null) throw new Exception("Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决"); + if (_orm.Ado.MasterPool == null) throw new Exception(CoreStrings.MasterPool_IsNull_UseTransaction); using (var conn = await _orm.Ado.MasterPool.GetAsync()) { _transaction = conn.Value.BeginTransaction(); @@ -230,12 +230,12 @@ async protected virtual Task> SplitExecuteInsertedAsync(int valuesLimit ret.AddRange(await this.RawExecuteInsertedAsync(cancellationToken)); } _transaction.Commit(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "提交", null)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.Commit, null)); } catch (Exception ex) { _transaction.Rollback(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "回滚", ex)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.RollBack, ex)); throw; } _transaction = null; diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select0Provider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select0Provider.cs index 3652ca52c..008dc3294 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select0Provider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select0Provider.cs @@ -144,7 +144,7 @@ public Expression ConvertStringPropertyToExpression(string property, bool fromFi break; } } - if (exp == null) throw new Exception($"无法匹配 {property}"); + if (exp == null) throw new Exception(CoreStrings.Cannot_Match_Property(property)); } else { @@ -160,7 +160,7 @@ public Expression ConvertStringPropertyToExpression(string property, bool fromFi { var tmp1 = field[x]; if (_commonUtils.GetTableByEntity(currentType).Properties.TryGetValue(tmp1, out var prop) == false) - throw new ArgumentException($"{currentType.DisplayCsharp()} 无法找到属性名 {tmp1}"); + throw new ArgumentException($"{currentType.DisplayCsharp()} {CoreStrings.NotFound_PropertyName(tmp1)}"); currentType = prop.PropertyType; currentExp = Expression.MakeMemberAccess(currentExp, prop); } @@ -176,7 +176,7 @@ public Expression ConvertStringPropertyToExpression(string property, bool fromFi public static MethodInfo GetMethodEnumerable(string methodName) => MethodEnumerableDic.GetOrAdd(methodName, et => { var methods = typeof(Enumerable).GetMethods().Where(a => a.Name == et); - if (et == "Select") + if (et == "Select") return methods.Where(a => a.GetParameters()[1].ParameterType.GetGenericTypeDefinition() == typeof(Func<,>)).FirstOrDefault(); return methods.FirstOrDefault(); }); @@ -254,7 +254,7 @@ public TSelect InnerJoin(Expression> exp) } public TSelect RightJoin(Expression> exp) { - if (exp == null) return this as TSelect; + if (exp == null) return this as TSelect; _tables[0].Parameter = exp.Parameters[0]; return this.InternalJoin(exp?.Body, SelectTableInfoType.RightJoin); } @@ -402,7 +402,7 @@ string GetToDeleteWhere(string alias) } public IDelete ToDelete() { - if (_tables[0].Table.Primarys.Any() == false) throw new Exception($"ToDelete 功能要求实体类 {_tables[0].Table.CsName} 必须有主键"); + if (_tables[0].Table.Primarys.Any() == false) throw new Exception(CoreStrings.Entity_Must_Primary_Key("ToDelete", _tables[0].Table.CsName)); var del = (_orm as BaseDbProvider).CreateDeleteProvider(null) as DeleteProvider; if (_tables[0].Table.Type != typeof(T1)) del.AsType(_tables[0].Table.Type); if (_params.Any()) del._params = new List(_params.ToArray()); @@ -436,7 +436,7 @@ public IDelete ToDelete() } public IUpdate ToUpdate() { - if (_tables[0].Table.Primarys.Any() == false) throw new Exception($"ToUpdate 功能要求实体类 {_tables[0].Table.CsName} 必须有主键"); + if (_tables[0].Table.Primarys.Any() == false) throw new Exception(CoreStrings.Entity_Must_Primary_Key("ToUpdate", _tables[0].Table.CsName)); var upd = (_orm as BaseDbProvider).CreateUpdateProvider(null) as UpdateProvider; if (_tables[0].Table.Type != typeof(T1)) upd.AsType(_tables[0].Table.Type); if (_params.Any()) upd._params = new List(_params.ToArray()); @@ -472,7 +472,7 @@ public IUpdate ToUpdate() protected List> GetTableRuleUnions() { var unions = new List>(); - var trs = _tableRules.Any() ? _tableRules : new List>(new [] { new Func((type, oldname) => null) }); + var trs = _tableRules.Any() ? _tableRules : new List>(new[] { new Func((type, oldname) => null) }); if (trs.Count == 1 && _tables.Any(a => a.Table.AsTableImpl != null && string.IsNullOrWhiteSpace(trs[0](a.Table.Type, a.Table.DbName)) == true)) { @@ -571,10 +571,10 @@ public TSelect AsAlias(Func aliasRule) } public TSelect AsType(Type entityType) { - if (entityType == typeof(object)) throw new Exception("ISelect.AsType 参数不支持指定为 object"); + if (entityType == typeof(object)) throw new Exception(CoreStrings.TypeAsType_NotSupport_Object("ISelect")); if (entityType == _tables[0].Table.Type) return this as TSelect; var newtb = _commonUtils.GetTableByEntity(entityType); - _tables[0].Table = newtb ?? throw new Exception("ISelect.AsType 参数错误,请传入正确的实体类型"); + _tables[0].Table = newtb ?? throw new Exception(CoreStrings.Type_AsType_Parameter_Error("ISelect")); if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); return this as TSelect; } @@ -619,14 +619,14 @@ void ParseFilter(DynamicFilterLogic logic, DynamicFilterInfo fi, bool isend) { case DynamicFilterOperator.Custom: var fiValueCustomArray = fi.Field?.ToString().Split(new[] { ' ' }, 2); - if (fiValueCustomArray.Length != 2) throw new ArgumentException("Custom 要求 Field 应该空格分割,并且长度为 2,格式:{静态方法名}{空格}{反射信息}"); - if (string.IsNullOrWhiteSpace(fiValueCustomArray[0])) throw new ArgumentException("Custom {静态方法名}不能为空,格式:{静态方法名}{空格}{反射信息}"); - if (string.IsNullOrWhiteSpace(fiValueCustomArray[1])) throw new ArgumentException("Custom {反射信息}不能为空,格式:{静态方法名}{空格}{反射信息}"); + if (fiValueCustomArray.Length != 2) throw new ArgumentException(CoreStrings.CustomFieldSeparatedBySpaces); + if (string.IsNullOrWhiteSpace(fiValueCustomArray[0])) throw new ArgumentException(CoreStrings.Custom_StaticMethodName_IsNotNull); + if (string.IsNullOrWhiteSpace(fiValueCustomArray[1])) throw new ArgumentException(CoreStrings.Custom_Reflection_IsNotNull); var fiValue1Type = Type.GetType(fiValueCustomArray[1]); - if (fiValue1Type == null) throw new ArgumentException($"Custom 找不到对应的{{反射信息}}:{fiValueCustomArray[1]}"); + if (fiValue1Type == null) throw new ArgumentException(CoreStrings.NotFound_Reflection(fiValueCustomArray[1])); var fiValue0Method = fiValue1Type.GetMethod(fiValueCustomArray[0], new Type[] { typeof(string) }); - if (fiValue0Method == null) throw new ArgumentException($"Custom 找不到对应的{{静态方法名}}:{fiValueCustomArray[0]}"); - if (MethodIsDynamicFilterCustomAttribute(fiValue0Method) == false) throw new ArgumentException($"Custom 对应的{{静态方法名}}:{fiValueCustomArray[0]} 未设置 [DynamicFilterCustomAttribute] 特性"); + if (fiValue0Method == null) throw new ArgumentException(CoreStrings.NotFound_Static_MethodName(fiValueCustomArray[0])); + if (MethodIsDynamicFilterCustomAttribute(fiValue0Method) == false) throw new ArgumentException(CoreStrings.Custom_StaticMethodName_NotSet_DynamicFilterCustom(fiValueCustomArray[0])); var fiValue0MethodReturn = fiValue0Method?.Invoke(null, new object[] { fi.Value?.ToString() })?.ToString(); exp = Expression.Call(typeof(SqlExt).GetMethod("InternalRawSql", BindingFlags.NonPublic | BindingFlags.Static), Expression.Constant(fiValue0MethodReturn, typeof(string))); break; @@ -664,20 +664,20 @@ void ParseFilter(DynamicFilterLogic logic, DynamicFilterInfo fi, bool isend) case DynamicFilterOperator.LessThanOrEqual: exp = Expression.Call(typeof(SqlExt).GetMethod("LessThanOrEqual").MakeGenericMethod(exp.Type), exp, Expression.Constant(Utils.GetDataReaderValue(exp.Type, fi.Value?.ToString()), exp.Type)); break; case DynamicFilterOperator.Range: var fiValueRangeArray = getFiListValue(); - if (fiValueRangeArray.Length != 2) throw new ArgumentException($"Range 要求 Value 应该逗号分割,并且长度为 2"); + if (fiValueRangeArray.Length != 2) throw new ArgumentException(CoreStrings.Range_Comma_Separateda_By2Char); exp = Expression.AndAlso( Expression.GreaterThanOrEqual(exp, Expression.Constant(Utils.GetDataReaderValue(exp.Type, fiValueRangeArray[0]), exp.Type)), Expression.LessThan(exp, Expression.Constant(Utils.GetDataReaderValue(exp.Type, fiValueRangeArray[1]), exp.Type))); break; case DynamicFilterOperator.DateRange: var fiValueDateRangeArray = getFiListValue(); - if (fiValueDateRangeArray?.Length != 2) throw new ArgumentException($"DateRange 要求 Value 应该逗号分割,并且长度为 2"); + if (fiValueDateRangeArray?.Length != 2) throw new ArgumentException(CoreStrings.DateRange_Comma_Separateda_By2Char); if (Regex.IsMatch(fiValueDateRangeArray[1], @"^\d\d\d\d[\-/]\d\d?[\-/]\d\d?$")) fiValueDateRangeArray[1] = DateTime.Parse(fiValueDateRangeArray[1]).AddDays(1).ToString("yyyy-MM-dd HH:mm:ss"); else if (Regex.IsMatch(fiValueDateRangeArray[1], @"^\d\d\d\d[\-/]\d\d?$")) fiValueDateRangeArray[1] = DateTime.Parse($"{fiValueDateRangeArray[1]}-01").AddMonths(1).ToString("yyyy-MM-dd HH:mm:ss"); else if (Regex.IsMatch(fiValueDateRangeArray[1], @"^\d\d\d\d$")) fiValueDateRangeArray[1] = DateTime.Parse($"{fiValueDateRangeArray[1]}-01-01").AddYears(1).ToString("yyyy-MM-dd HH:mm:ss"); else if (Regex.IsMatch(fiValueDateRangeArray[1], @"^\d\d\d\d[\-/]\d\d?[\-/]\d\d? \d\d?$")) fiValueDateRangeArray[1] = DateTime.Parse($"{fiValueDateRangeArray[1]}:00:00").AddHours(1).ToString("yyyy-MM-dd HH:mm:ss"); else if (Regex.IsMatch(fiValueDateRangeArray[1], @"^\d\d\d\d[\-/]\d\d?[\-/]\d\d? \d\d?:\d\d?$")) fiValueDateRangeArray[1] = DateTime.Parse($"{fiValueDateRangeArray[1]}:00").AddMinutes(1).ToString("yyyy-MM-dd HH:mm:ss"); - else throw new ArgumentException($"DateRange 要求 Value[1] 格式必须为:yyyy、yyyy-MM、yyyy-MM-dd、yyyy-MM-dd HH、yyyy、yyyy-MM-dd HH:mm"); + else throw new ArgumentException(CoreStrings.DateRange_DateFormat_yyyy); if (Regex.IsMatch(fiValueDateRangeArray[0], @"^\d\d\d\d[\-/]\d\d?$")) fiValueDateRangeArray[0] = DateTime.Parse($"{fiValueDateRangeArray[0]}-01").ToString("yyyy-MM-dd HH:mm:ss"); else if (Regex.IsMatch(fiValueDateRangeArray[0], @"^\d\d\d\d$")) fiValueDateRangeArray[0] = DateTime.Parse($"{fiValueDateRangeArray[0]}-01-01").ToString("yyyy-MM-dd HH:mm:ss"); @@ -774,7 +774,8 @@ static bool MethodIsDynamicFilterCustomAttribute(MethodInfo method) => _dicMetho } catch { } - var dyattr = attrs?.Where(a => { + var dyattr = attrs?.Where(a => + { return ((a as Attribute)?.TypeId as Type)?.Name == "DynamicFilterCustomAttribute"; }).FirstOrDefault(); return dyattr != null; @@ -800,7 +801,7 @@ public TSelect DisableGlobalFilter(params string[] name) public TSelect ForUpdate(bool noawait = false) { if (_transaction == null && _orm.Ado.TransactionCurrentThread == null) - throw new Exception("安全起见,请务必在事务开启之后,再使用 ForUpdate"); + throw new Exception($"{CoreStrings.Begin_Transaction_Then_ForUpdate}"); switch (_orm.Ado.DataType) { case DataType.MySql: diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select0ProviderReader.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select0ProviderReader.cs index d3612d7d8..6de1859e5 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select0ProviderReader.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select0ProviderReader.cs @@ -1,4 +1,4 @@ -using FreeSql.Internal.Model; +using FreeSql.Internal.Model; using System; using System.Collections; using System.Collections.Concurrent; @@ -21,13 +21,13 @@ partial class Select0Provider { public DataTable ToDataTableByPropertyName(string[] properties) { - if (properties?.Any() != true) throw new ArgumentException($"properties 参数不能为空"); + if (properties?.Any() != true) throw new ArgumentException($"{CoreStrings.Properties_Cannot_Null}"); var sbfield = new StringBuilder(); for (var propIdx = 0; propIdx < properties.Length; propIdx++) { var property = properties[propIdx]; var exp = ConvertStringPropertyToExpression(property); - if (exp == null) throw new Exception($"{property} 属性名无法找到"); + if (exp == null) throw new Exception(CoreStrings.Property_Cannot_Find(property)); var field = _commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null); if (propIdx > 0) sbfield.Append(", "); sbfield.Append(field); @@ -225,7 +225,7 @@ internal void ToListChunkPrivate(int chunkSize, Action>> done, bool includeNestedMembers = false) { - if (_selectExpression != null) throw new ArgumentException("Chunk 功能之前不可使用 Select"); + if (_selectExpression != null) throw new ArgumentException(CoreStrings.Before_Chunk_Cannot_Use_Select); this.ToListChunkPrivate(size, done, includeNestedMembers == false ? this.GetAllFieldExpressionTreeLevel2() : this.GetAllFieldExpressionTreeLevelAll(), null); } @@ -776,7 +776,7 @@ public TSelect InternalJoin(Expression exp, SelectTableInfoType joinType) protected TSelect InternalJoin(Expression exp, SelectTableInfoType joinType) { var tb = _commonUtils.GetTableByEntity(typeof(T2)); - if (tb == null) throw new ArgumentException("T2 类型错误"); + if (tb == null) throw new ArgumentException(CoreStrings.T2_Type_Error); _tables.Add(new SelectTableInfo { Table = tb, Alias = $"IJ{_tables.Count}", On = null, Type = joinType }); _commonExpression.ExpressionJoinLambda(_tables, joinType, exp, null, _whereGlobalFilter); return this as TSelect; @@ -817,7 +817,7 @@ protected string InternalToSql(Expression select, FieldAliasOptions fie protected string InternalGetInsertIntoToSql(string tableName, Expression select) { var tb = _orm.CodeFirst.GetTableByEntity(typeof(TTargetEntity)); - if (tb == null) throw new ArgumentException($"ISelect.InsertInto() 类型错误: {typeof(TTargetEntity).DisplayCsharp()}"); + if (tb == null) throw new ArgumentException(CoreStrings.InsertInto_TypeError(typeof(TTargetEntity).DisplayCsharp())); if (string.IsNullOrEmpty(tableName)) tableName = tb.DbName; if (_orm.CodeFirst.IsSyncStructureToLower) tableName = tableName.ToLower(); if (_orm.CodeFirst.IsSyncStructureToUpper) tableName = tableName.ToUpper(); @@ -829,8 +829,8 @@ protected string InternalGetInsertIntoToSql(string tableName, Exp _commonExpression.ReadAnonymousField(_tables, field, map, ref index, select, null, null, _whereGlobalFilter, null, false); //不走 DTO 映射,不处理 IncludeMany var childs = map.Childs; - if (childs.Any() == false) throw new ArgumentException($"ISelect.InsertInto() 未选择属性: {typeof(TTargetEntity).DisplayCsharp()}"); - foreach(var col in tb.Columns.Values) + if (childs.Any() == false) throw new ArgumentException(CoreStrings.InsertInto_No_Property_Selected(typeof(TTargetEntity).DisplayCsharp())); + foreach (var col in tb.Columns.Values) { if (col.Attribute.IsIdentity && string.IsNullOrEmpty(col.DbInsertValue)) continue; if (col.Attribute.CanInsert == false) continue; @@ -923,13 +923,13 @@ protected TReturn InternalToAggregate(Expression select) #else public Task ToDataTableByPropertyNameAsync(string[] properties, CancellationToken cancellationToken) { - if (properties?.Any() != true) throw new ArgumentException($"properties 参数不能为空"); + if (properties?.Any() != true) throw new ArgumentException($"{CoreStrings.Properties_Cannot_Null}"); var sbfield = new StringBuilder(); for (var propIdx = 0; propIdx < properties.Length; propIdx++) { var property = properties[propIdx]; var exp = ConvertStringPropertyToExpression(property); - if (exp == null) throw new Exception($"{property} 属性名无法找到"); + if (exp == null) throw new Exception(CoreStrings.Property_Cannot_Find(property)); var field = _commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null); if (propIdx > 0) sbfield.Append(", "); sbfield.Append(field); diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select1Provider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select1Provider.cs index 28dba3c33..d402ccbf3 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select1Provider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select1Provider.cs @@ -32,7 +32,7 @@ protected ISelect InternalFrom(LambdaExpression lambdaExp) for (var a = 1; a < lambdaExp.Parameters.Count; a++) { var tb = _commonUtils.GetTableByEntity(lambdaExp.Parameters[a].Type); - if (tb == null) throw new ArgumentException($"{lambdaExp.Parameters[a].Name} 类型错误"); + if (tb == null) throw new ArgumentException(CoreStrings.Type_Error_Name(lambdaExp.Parameters[a].Name)); _tables.Add(new SelectTableInfo { Table = tb, Alias = lambdaExp.Parameters[a].Name, On = null, Type = SelectTableInfoType.From }); } } @@ -81,8 +81,7 @@ protected ISelect InternalFrom(LambdaExpression lambdaExp) case "LeftJoin": this.InternalJoin(expCall.Arguments[0], SelectTableInfoType.LeftJoin); break; case "InnerJoin": this.InternalJoin(expCall.Arguments[0], SelectTableInfoType.InnerJoin); break; case "RightJoin": this.InternalJoin(expCall.Arguments[0], SelectTableInfoType.RightJoin); break; - - default: throw new NotImplementedException($"未实现 {expCall.Method.Name}"); + default: throw new NotImplementedException(CoreStrings.Not_Implemented_Name(expCall.Method.Name)); } } } @@ -118,7 +117,7 @@ public double Avg(Expression> column) public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class; public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class; public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class; - + public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class where T11 : class; public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class where T11 : class where T12 : class; public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class where T11 : class where T12 : class where T13 : class; @@ -244,7 +243,7 @@ MemberInitExpression GetIncludeManyNewInitExpression(IncludeManyNewInit imni) var splitKeys = fim.Item1.Split('.'); var otherRetItem = otherRet[fim.Item3]; var otherRetItemType = _tables[0].Table.Type; - foreach(var splitKey in splitKeys) + foreach (var splitKey in splitKeys) { otherRetItem = _orm.GetEntityValueWithPropertyName(otherRetItemType, otherRetItem, splitKey); otherRetItemType = _orm.CodeFirst.GetTableByEntity(otherRetItemType).Properties[splitKey].PropertyType; @@ -263,7 +262,7 @@ Expression> GetToListDtoSelector() .Where(a => a.Value.CsType != a.Value.Attribute.MapType) .Select(a => new { DtoProperty = typeof(TDto).GetProperty(a.Value.CsName), EntityProperty = _tables[0].Table.Properties[a.Value.CsName], Column = a.Value }) .Where(a => a.DtoProperty != null) - .Select(a => + .Select(a => a.DtoProperty.PropertyType == a.EntityProperty.PropertyType ? Expression.Bind(a.DtoProperty, Expression.MakeMemberAccess(expParam, a.EntityProperty)) : Expression.Bind(a.DtoProperty, Expression.Convert(Expression.MakeMemberAccess(expParam, a.EntityProperty), a.DtoProperty.PropertyType)) @@ -408,13 +407,13 @@ public bool Any(Expression> exp) public ISelect IncludeByPropertyName(string property) { var exp = ConvertStringPropertyToExpression(property, true); - if (exp == null) throw new ArgumentException($"{nameof(property)} 无法解析为表达式树"); + if (exp == null) throw new ArgumentException($"{CoreStrings.Cannot_Resolve_ExpressionTree(nameof(property))}"); var memExp = exp as MemberExpression; - if (memExp == null) throw new ArgumentException($"{nameof(property)} 无法解析为表达式树2"); + if (memExp == null) throw new ArgumentException($"{CoreStrings.Cannot_Resolve_ExpressionTree(nameof(property))}2"); var parTb = _commonUtils.GetTableByEntity(memExp.Expression.Type); - if (parTb == null) throw new ArgumentException($"{nameof(property)} 无法解析为表达式树3"); + if (parTb == null) throw new ArgumentException($"{CoreStrings.Cannot_Resolve_ExpressionTree(nameof(property))}3"); var parTbref = parTb.GetTableRef(memExp.Member.Name, true); - if (parTbref == null) throw new ArgumentException($"{nameof(property)} 不是有效的导航属性"); + if (parTbref == null) throw new ArgumentException(CoreStrings.Not_Valid_Navigation_Property(nameof(property))); switch (parTbref.RefType) { case TableRefType.ManyToMany: @@ -422,7 +421,7 @@ public ISelect IncludeByPropertyName(string property) var funcType = typeof(Func<,>).MakeGenericType(_tables[0].Table.Type, typeof(IEnumerable<>).MakeGenericType(parTbref.RefEntityType)); var navigateSelector = Expression.Lambda(funcType, exp, _tables[0].Parameter); var incMethod = this.GetType().GetMethod("IncludeMany"); - if (incMethod == null) throw new Exception("运行时错误,反射获取 IncludeMany 方法失败"); + if (incMethod == null) throw new Exception(CoreStrings.RunTimeError_Reflection_IncludeMany); incMethod.MakeGenericMethod(parTbref.RefEntityType).Invoke(this, new object[] { navigateSelector, null }); break; case TableRefType.ManyToOne: @@ -441,10 +440,10 @@ public ISelect Include(Expression> navigateSe { var expBody = navigateSelector?.Body; if (expBody == null) return this; - if (expBody.NodeType != ExpressionType.MemberAccess) throw new Exception("Include 参数类型错误,表达式类型应该为 MemberAccess"); - if (typeof(IEnumerable).IsAssignableFrom(expBody.Type)) throw new Exception("Include 参数类型错误,集合属性请使用 IncludeMany"); + if (expBody.NodeType != ExpressionType.MemberAccess) throw new Exception(CoreStrings.Include_ParameterType_Error_Use_MemberAccess); + if (typeof(IEnumerable).IsAssignableFrom(expBody.Type)) throw new Exception(CoreStrings.Include_ParameterType_Error_Use_IncludeMany); var tb = _commonUtils.GetTableByEntity(expBody.Type); - if (tb == null) throw new Exception("Include 参数类型错误"); + if (tb == null) throw new Exception(CoreStrings.Include_ParameterType_Error); _isIncluded = true; _tables[0].Parameter = navigateSelector.Parameters[0]; @@ -472,18 +471,18 @@ static NativeTuple> GetExpressionSta isbreak = true; break; default: - throw new Exception($"表达式错误,它不是连续的 MemberAccess 类型:{exp}"); + throw new Exception(CoreStrings.Expression_Error_Use_Successive_MemberAccess_Type(exp)); } } - if (param == null) throw new Exception($"表达式错误,它的顶级对象不是 ParameterExpression:{exp}"); + if (param == null) throw new Exception(CoreStrings.Expression_Error_Use_ParameterExpression(exp)); return NativeTuple.Create(param, members.ToList()); } static MethodInfo GetEntityValueWithPropertyNameMethod = typeof(EntityUtilExtensions).GetMethod("GetEntityValueWithPropertyName"); static ConcurrentDictionary> _dicTypeMethod = new ConcurrentDictionary>(); public ISelect IncludeMany(Expression>> navigateSelector, Action> then = null) where TNavigate : class { - var throwNavigateSelector = new Exception("IncludeMany 参数1 类型错误,表达式类型应该为 MemberAccess"); - + var throwNavigateSelector = new Exception(CoreStrings.IncludeMany_ParameterType_Error_Use_MemberAccess); + var expBody = navigateSelector?.Body; if (expBody == null) return this; if (expBody.NodeType == ExpressionType.Convert) expBody = (expBody as UnaryExpression)?.Operand; //- 兼容 Vb.Net 无法使用 IncludeMany 的问题; @@ -492,7 +491,7 @@ public ISelect IncludeMany(Expression> selectExp = null; while (expBody.NodeType == ExpressionType.Call) { - throwNavigateSelector = new Exception($"IncludeMany {nameof(navigateSelector)} 参数类型错误,正确格式: a.collections.Take(1).Where(c => c.aid == a.id).Select(a => new TNavigate {{ }})"); + throwNavigateSelector = new Exception(CoreStrings.IncludeMany_ParameterTypeError(nameof(navigateSelector))); var callExp = (expBody as MethodCallExpression); switch (callExp.Method.Name) { @@ -504,7 +503,7 @@ public ISelect IncludeMany(Expression>); - if (selectExp?.Parameters.Count != 1) throw new Exception($"IncludeMany {nameof(navigateSelector)} 参数错误,Select 只可以使用一个参数的方法,正确格式: .Select(t => new TNavigate {{ }})"); + if (selectExp?.Parameters.Count != 1) throw new Exception(CoreStrings.IncludeMany_ParameterError_OnlyUseOneParameter(nameof(navigateSelector))); break; default: throw throwNavigateSelector; } @@ -519,10 +518,10 @@ public ISelect IncludeMany(Expression IncludeMany(Expression IncludeMany(Expression) + if (tbref.RefType == TableRefType.OneToMany && _includeManySubListOneToManyTempValue1 != null && _includeManySubListOneToManyTempValue1 is List) { fillOneToManyData(_includeManySubListOneToManyTempValue1 as List, _commonUtils.GetTableByEntity(tbref.RefEntityType)); return; diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/SelectGroupingProvider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/SelectGroupingProvider.cs index 2f0e0703d..6dff39078 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/SelectGroupingProvider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/SelectGroupingProvider.cs @@ -150,7 +150,7 @@ public string InternalToSql(Expression select, FieldAliasOptions fieldAlias = Fi public string InternalToSql(string field) { if (string.IsNullOrEmpty(field)) - throw new ArgumentException("参数 field 未指定"); + throw new ArgumentException(CoreStrings.Parameter_Field_NotSpecified); var isNestedPageSql = false; switch (_orm.Ado.DataType) diff --git a/FreeSql/Internal/CommonProvider/UpdateProvider.cs b/FreeSql/Internal/CommonProvider/UpdateProvider.cs index 71af0381c..c70ba5164 100644 --- a/FreeSql/Internal/CommonProvider/UpdateProvider.cs +++ b/FreeSql/Internal/CommonProvider/UpdateProvider.cs @@ -132,7 +132,7 @@ protected void ValidateVersionAndThrow(int affrows, string sql, DbParameter[] db if (_table.VersionColumn != null && _source.Count > 0) { if (affrows != _source.Count) - throw new DbUpdateVersionException($"记录可能不存在,或者【行级乐观锁】版本过旧,更新数量{_source.Count},影响的行数{affrows}。", _table, sql, dbParms, affrows, _source.Select(a => (object)a)); + throw new DbUpdateVersionException(CoreStrings.DbUpdateVersionException_RowLevelOptimisticLock(_source.Count, affrows), _table, sql, dbParms, affrows, _source.Select(a => (object)a)); foreach (var d in _source) { if (_table.VersionColumn.Attribute.MapType == typeof(byte[])) @@ -224,7 +224,7 @@ protected virtual int SplitExecuteAffrows(int valuesLimit, int parameterLimit) } else { - if (_orm.Ado.MasterPool == null) throw new Exception("Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决"); + if (_orm.Ado.MasterPool == null) throw new Exception(CoreStrings.MasterPool_IsNull_UseTransaction); using (var conn = _orm.Ado.MasterPool.Get()) { _transaction = conn.Value.BeginTransaction(); @@ -239,12 +239,12 @@ protected virtual int SplitExecuteAffrows(int valuesLimit, int parameterLimit) ret += this.RawExecuteAffrows(); } _transaction.Commit(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "提交", null)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.Commit, null)); } catch (Exception ex) { _transaction.Rollback(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "回滚", ex)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.RollBack, ex)); throw; } _transaction = null; @@ -298,7 +298,7 @@ protected virtual List SplitExecuteUpdated(int valuesLimit, int parameterLim } else { - if (_orm.Ado.MasterPool == null) throw new Exception("Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决"); + if (_orm.Ado.MasterPool == null) throw new Exception(CoreStrings.MasterPool_IsNull_UseTransaction); using (var conn = _orm.Ado.MasterPool.Get()) { _transaction = conn.Value.BeginTransaction(); @@ -313,12 +313,12 @@ protected virtual List SplitExecuteUpdated(int valuesLimit, int parameterLim ret.AddRange(this.RawExecuteUpdated()); } _transaction.Commit(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "提交", null)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.Commit, null)); } catch (Exception ex) { _transaction.Rollback(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "回滚", ex)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.RollBack, ex)); throw; } _transaction = null; @@ -428,7 +428,7 @@ public static void AuditDataValue(object sender, T1 data, IFreeSql orm, TableInf if (orm.Aop.AuditValueHandler == null) return; if (data == null || table == null) return; if (typeof(T1) == typeof(object) && new[] { table.Type, table.TypeLazy }.Contains(data.GetType()) == false) - throw new Exception($"操作的数据类型({data.GetType().DisplayCsharp()}) 与 AsType({table.Type.DisplayCsharp()}) 不一致,请检查。"); + throw new Exception(CoreStrings.DataType_AsType_Inconsistent(data.GetType().DisplayCsharp(), table.Type.DisplayCsharp())); foreach (var col in table.Columns.Values) { object val = col.GetValue(data); @@ -558,9 +558,12 @@ public IUpdate Set(Expression> exp) if (initAssignExp == null) continue; var memberName = initExp.Bindings[a].Member.Name; if (_table.ColumnsByCsIgnore.ContainsKey(memberName)) continue; - if (_table.ColumnsByCs.TryGetValue(memberName, out var col) == false) throw new Exception($"找不到属性:{memberName}"); - var memberValue = _commonExpression.ExpressionLambdaToSql(initAssignExp.Expression, new CommonExpression.ExpTSC { isQuoteName = true, - mapType = initAssignExp.Expression is BinaryExpression ? null : col.Attribute.MapType }); + if (_table.ColumnsByCs.TryGetValue(memberName, out var col) == false) throw new Exception(CoreStrings.NotFound_Property(memberName)); + var memberValue = _commonExpression.ExpressionLambdaToSql(initAssignExp.Expression, new CommonExpression.ExpTSC + { + isQuoteName = true, + mapType = initAssignExp.Expression is BinaryExpression ? null : col.Attribute.MapType + }); _setIncr.Append(", ").Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = ").Append(memberValue); } } @@ -573,9 +576,12 @@ public IUpdate Set(Expression> exp) { var memberName = newExp.Members[a].Name; if (_table.ColumnsByCsIgnore.ContainsKey(memberName)) continue; - if (_table.ColumnsByCs.TryGetValue(memberName, out var col) == false) throw new Exception($"找不到属性:{memberName}"); - var memberValue = _commonExpression.ExpressionLambdaToSql(newExp.Arguments[a], new CommonExpression.ExpTSC { isQuoteName = true, - mapType = newExp.Arguments[a] is BinaryExpression ? null : col.Attribute.MapType }); + if (_table.ColumnsByCs.TryGetValue(memberName, out var col) == false) throw new Exception(CoreStrings.NotFound_Property(memberName)); + var memberValue = _commonExpression.ExpressionLambdaToSql(newExp.Arguments[a], new CommonExpression.ExpTSC + { + isQuoteName = true, + mapType = newExp.Arguments[a] is BinaryExpression ? null : col.Attribute.MapType + }); _setIncr.Append(", ").Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = ").Append(memberValue); } } @@ -672,7 +678,7 @@ public IUpdate DisableGlobalFilter(params string[] name) protected string WhereCaseSource(string CsName, Func thenValue) { if (_source.Any() == false) return null; - if (_table.ColumnsByCs.ContainsKey(CsName) == false) throw new Exception($"找不到 {CsName} 对应的列"); + if (_table.ColumnsByCs.ContainsKey(CsName) == false) throw new Exception(CoreStrings.NotFound_CsName_Column(CsName)); if (thenValue == null) throw new ArgumentNullException(nameof(thenValue)); if (_source.Count == 0) return null; @@ -757,10 +763,10 @@ public IUpdate AsTable(string tableName) } public IUpdate AsType(Type entityType) { - if (entityType == typeof(object)) throw new Exception("IUpdate.AsType 参数不支持指定为 object"); + if (entityType == typeof(object)) throw new Exception(CoreStrings.TypeAsType_NotSupport_Object("IUpdate")); if (entityType == _table.Type) return this; var newtb = _commonUtils.GetTableByEntity(entityType); - _table = newtb ?? throw new Exception("IUpdate.AsType 参数错误,请传入正确的实体类型"); + _table = newtb ?? throw new Exception(CoreStrings.Type_AsType_Parameter_Error("IUpdate")); _tempPrimarys = _table.Primarys; if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); IgnoreCanUpdate(); @@ -1003,7 +1009,7 @@ public virtual void ToSqlWhere(StringBuilder sb) sb.Append(" \r\nWHERE "); if (_source.Any()) { - if (_tempPrimarys.Any() == false) throw new ArgumentException($"{_table.Type.DisplayCsharp()} 没有定义主键,无法使用 SetSource,请尝试 SetDto"); + if (_tempPrimarys.Any() == false) throw new ArgumentException(CoreStrings.NoPrimaryKey_UseSetDto(_table.Type.DisplayCsharp())); sb.Append('(').Append(_commonUtils.WhereItems(_tempPrimarys, "", _source)).Append(')'); } diff --git a/FreeSql/Internal/CommonProvider/UpdateProviderAsync.cs b/FreeSql/Internal/CommonProvider/UpdateProviderAsync.cs index 8a2127fe8..b06f9d792 100644 --- a/FreeSql/Internal/CommonProvider/UpdateProviderAsync.cs +++ b/FreeSql/Internal/CommonProvider/UpdateProviderAsync.cs @@ -51,7 +51,7 @@ async protected virtual Task SplitExecuteAffrowsAsync(int valuesLimit, int } else { - if (_orm.Ado.MasterPool == null) throw new Exception("Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决"); + if (_orm.Ado.MasterPool == null) throw new Exception(CoreStrings.MasterPool_IsNull_UseTransaction); using (var conn = await _orm.Ado.MasterPool.GetAsync()) { _transaction = conn.Value.BeginTransaction(); @@ -66,12 +66,12 @@ async protected virtual Task SplitExecuteAffrowsAsync(int valuesLimit, int ret += await this.RawExecuteAffrowsAsync(cancellationToken); } _transaction.Commit(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "提交", null)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.Commit, null)); } catch (Exception ex) { _transaction.Rollback(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "回滚", ex)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.RollBack, ex)); throw; } _transaction = null; @@ -124,7 +124,7 @@ async protected virtual Task> SplitExecuteUpdatedAsync(int valuesLimit, } else { - if (_orm.Ado.MasterPool == null) throw new Exception("Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决"); + if (_orm.Ado.MasterPool == null) throw new Exception(CoreStrings.MasterPool_IsNull_UseTransaction); using (var conn = await _orm.Ado.MasterPool.GetAsync()) { _transaction = conn.Value.BeginTransaction(); @@ -139,12 +139,12 @@ async protected virtual Task> SplitExecuteUpdatedAsync(int valuesLimit, ret.AddRange(await this.RawExecuteUpdatedAsync(cancellationToken)); } _transaction.Commit(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "提交", null)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.Commit, null)); } catch (Exception ex) { _transaction.Rollback(); - _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, "回滚", ex)); + _orm.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(transBefore, CoreStrings.RollBack, ex)); throw; } _transaction = null; diff --git a/FreeSql/Internal/ObjectPool/ObjectPool.cs b/FreeSql/Internal/ObjectPool/ObjectPool.cs index d75d684ef..d2576de3c 100644 --- a/FreeSql/Internal/ObjectPool/ObjectPool.cs +++ b/FreeSql/Internal/ObjectPool/ObjectPool.cs @@ -123,12 +123,12 @@ private void CheckAvailable(int interval) { var conn = GetFree(false); - if (conn == null) throw new Exception($"CheckAvailable: Failed to get resource {this.Statistics}"); - + if (conn == null) throw new Exception(CoreStrings.Available_Failed_Get_Resource("CheckAvailable", this.Statistics)); + try { - if (Policy.OnCheckAvailable(conn) == false) throw new Exception("CheckAvailable: An exception needs to be thrown"); + if (Policy.OnCheckAvailable(conn) == false) throw new Exception(CoreStrings.Available_Thrown_Exception("CheckAvailable")); break; } @@ -187,22 +187,22 @@ protected bool LiveCheckAvailable() try { - + var conn = GetFree(false); - if (conn == null) throw new Exception($"LiveCheckAvailable: Failed to get resource {this.Statistics}"); - + if (conn == null) throw new Exception(CoreStrings.Available_Failed_Get_Resource("LiveCheckAvailable", this.Statistics)); + try { - - if (Policy.OnCheckAvailable(conn) == false) throw new Exception("LiveCheckAvailable: An exception needs to be thrown"); - + + if (Policy.OnCheckAvailable(conn) == false) throw new Exception(CoreStrings.Available_Thrown_Exception("LiveCheckAvailable")); + } finally { - + Return(conn); } - + } catch { @@ -275,11 +275,10 @@ private Object GetFree(bool checkAvailable) { if (running == false) - throw new ObjectDisposedException($"【{Policy.Name}】The ObjectPool has been disposed, see: https://github.com/dotnetcore/FreeSql/discussions/1079"); + throw new ObjectDisposedException(CoreStrings.Policy_ObjectPool_Dispose(Policy.Name)); if (checkAvailable && UnavailableException != null) - throw new Exception($"【{Policy.Name}】Block access and wait for recovery: {UnavailableException?.Message}, see: https://github.com/dotnetcore/FreeSql/discussions/1080", UnavailableException); - //throw new Exception($"【{Policy.Name}】状态不可用,等待后台检查程序恢复方可使用。{UnavailableException?.Message}"); + throw new Exception(CoreStrings.Policy_Status_NotAvailable(Policy.Name,UnavailableException?.Message), UnavailableException); if ((_freeObjects.TryPop(out var obj) == false || obj == null) && _allObjects.Count < Policy.PoolSize) { @@ -341,7 +340,7 @@ public Object Get(TimeSpan? timeout = null) Policy.OnGetTimeout(); if (Policy.IsThrowGetTimeoutException) - throw new TimeoutException($"【{Policy.Name}】ObjectPool.Get() timeout {timeout.Value.TotalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081"); + throw new TimeoutException(CoreStrings.ObjectPool_Get_Timeout(Policy.Name, "Get", timeout.Value.TotalSeconds)); return null; } @@ -375,7 +374,7 @@ async public Task> GetAsync() { if (Policy.AsyncGetCapacity > 0 && _getAsyncQueue.Count >= Policy.AsyncGetCapacity - 1) - throw new OutOfMemoryException($"【{Policy.Name}】ObjectPool.GetAsync() The queue is too long. Policy.AsyncGetCapacity = {Policy.AsyncGetCapacity}"); + throw new OutOfMemoryException(CoreStrings.ObjectPool_GetAsync_Queue_Long(Policy.Name, Policy.AsyncGetCapacity)); var tcs = new TaskCompletionSource>(); diff --git a/FreeSql/Internal/UtilsExpressionTree.cs b/FreeSql/Internal/UtilsExpressionTree.cs index 1aa460ea4..ff5fffa12 100644 --- a/FreeSql/Internal/UtilsExpressionTree.cs +++ b/FreeSql/Internal/UtilsExpressionTree.cs @@ -87,7 +87,7 @@ internal static TableInfo GetTableByEntity(Type entity, CommonUtils common) else colattr.IsIgnore = true; //Navigate 错误提示 var pnvAttr = common.GetEntityNavigateAttribute(trytb.Type, p); - if (pnvAttr != null) throw new Exception($"【导航属性】{trytb.Type.DisplayCsharp()}.{p.Name} 缺少 set 属性"); + if (pnvAttr != null) throw new Exception(CoreStrings.Navigation_Missing_SetProperty(trytb.Type.DisplayCsharp(),p.Name)); } if (tp == null && colattr?.IsIgnore != true) { @@ -381,8 +381,8 @@ internal static TableInfo GetTableByEntity(Type entity, CommonUtils common) colattr.DbType = Regex.Replace(colattr.DbType, decimalPatten, $"$1({colattr.Precision},{colattr.Scale})"); } - if (trytb.Columns.ContainsKey(colattr.Name)) throw new Exception($"ColumnAttribute.Name {colattr.Name} 重复存在,请检查(注意:不区分大小写)"); - if (trytb.ColumnsByCs.ContainsKey(p.Name)) throw new Exception($"属性名 {p.Name} 重复存在,请检查(注意:不区分大小写)"); + if (trytb.Columns.ContainsKey(colattr.Name)) throw new Exception(CoreStrings.Duplicate_ColumnAttribute(colattr.Name)); + if (trytb.ColumnsByCs.ContainsKey(p.Name)) throw new Exception(CoreStrings.Duplicate_PropertyName(p.Name)); trytb.Columns.Add(colattr.Name, col); trytb.ColumnsByCs.Add(p.Name, col); @@ -392,7 +392,7 @@ internal static TableInfo GetTableByEntity(Type entity, CommonUtils common) if (trytb.VersionColumn != null) { if (trytb.VersionColumn.Attribute.MapType.IsNullableType() || trytb.VersionColumn.Attribute.MapType.IsNumberType() == false && trytb.VersionColumn.Attribute.MapType != typeof(byte[])) - throw new Exception($"属性{trytb.VersionColumn.CsName} 被标注为行锁(乐观锁)(IsVersion),但其必须为数字类型 或者 byte[],并且不可为 Nullable"); + throw new Exception(CoreStrings.Properties_AsRowLock_Must_Numeric_Byte(trytb.VersionColumn.CsName)); } tbattr?.ParseAsTable(trytb); @@ -550,7 +550,7 @@ internal static TableInfo GetTableByEntity(Type entity, CommonUtils common) StringBuilder cscode = null; if (common.CodeFirst.IsLazyLoading && propsLazy.Any()) { - if (trytb.Type.IsPublic == false && trytb.Type.IsNestedPublic == false) throw new Exception($"【延时加载】实体类型 {trytbTypeName} 必须声明为 public"); + if (trytb.Type.IsPublic == false && trytb.Type.IsNestedPublic == false) throw new Exception(CoreStrings.LazyLoading_EntityMustDeclarePublic(trytbTypeName)); trytbTypeLazyName = $"FreeSqlLazyEntity__{Regex.Replace(trytbTypeName, @"[^\w\d]", "_")}"; @@ -576,14 +576,14 @@ internal static TableInfo GetTableByEntity(Type entity, CommonUtils common) { cscode.AppendLine("}"); Assembly assembly = null; - if (MethodLazyLoadingComplier.Value == null) throw new Exception("【延时加载】功能需要安装 FreeSql.Extensions.LazyLoading.dll,可前往 nuget 下载"); + if (MethodLazyLoadingComplier.Value == null) throw new Exception(CoreStrings.Install_FreeSql_Extensions_LazyLoading); try { assembly = MethodLazyLoadingComplier.Value.Invoke(null, new object[] { cscode.ToString() }) as Assembly; } catch (Exception ex) { - throw new Exception($"【延时加载】{trytbTypeName} 编译错误:{ex.Message}\r\n\r\n{cscode}"); + throw new Exception(CoreStrings.LazyLoading_CompilationError(trytbTypeName, ex.Message, cscode)); ; } var type = assembly.GetExportedTypes()/*.DefinedTypes*/.Where(a => a.FullName.EndsWith(trytbTypeLazyName)).FirstOrDefault(); trytb.TypeLazy = type; @@ -618,7 +618,7 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo if (typeof(IEnumerable).IsAssignableFrom(pnv.PropertyType) == false) return; if (trytb.Primarys.Any() == false) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 解析错误,实体类型 {trytbTypeName} 缺少主键标识,[Column(IsPrimary = true)]"); + nvref.Exception = new Exception(CoreStrings.Navigation_ParsingError_EntityMissingPrimaryKey(trytbTypeName, pnv.Name, trytbTypeName)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; return; @@ -651,7 +651,7 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo if (isManyToMany == false) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,实体类型 {tbrefTypeName} 必须存在对应的 [Navigate(ManyToMany = x)] 集合属性"); + nvref.Exception = new Exception(CoreStrings.ManyToMany_ParsingError_EntityMustHas_NavigateCollection(trytbTypeName, pnv.Name, tbrefTypeName)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; return; @@ -674,7 +674,7 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo { if (tbref.Primarys.Any() == false) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,实体类型 {tbrefTypeName} 缺少主键标识,[Column(IsPrimary = true)]"); + nvref.Exception = new Exception(CoreStrings.ManyToMany_ParsingError_EntityMissing_PrimaryKey(trytbTypeName, pnv.Name, tbrefTypeName)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; return; @@ -773,7 +773,7 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo } catch (Exception ex) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,中间类 {tbmid.CsName}.{midTypePropsTrytb.Name} 错误:{ex.Message}"); + nvref.Exception = new Exception(CoreStrings.ManyToMany_ParsingError_IntermediateClass_ErrorMessage(trytbTypeName, pnv.Name, tbmid.CsName, midTypePropsTrytb.Name, ex.Message)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; } @@ -781,7 +781,7 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo { if (trytbTf.RefType != TableRefType.ManyToOne && trytbTf.RefType != TableRefType.OneToOne) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,中间类 {tbmid.CsName}.{midTypePropsTrytb.Name} 导航属性不是【ManyToOne】或【OneToOne】"); + nvref.Exception = new Exception(CoreStrings.ManyToMany_ParsingError_IntermediateClass_NotManyToOne_OneToOne(trytbTypeName, pnv.Name, tbmid.CsName, midTypePropsTrytb.Name)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; } @@ -820,7 +820,7 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo } catch (Exception ex) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {tbrefTypeName}.{pnv.Name} 解析错误,中间类 {tbmid.CsName}.{midTypePropsTbref.Name} 错误:{ex.Message}"); + nvref.Exception = new Exception(CoreStrings.ManyToMany_ParsingError_IntermediateClass_ErrorMessage(trytbTypeName, pnv.Name, tbmid.CsName, midTypePropsTbref.Name, ex.Message)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; } @@ -828,7 +828,7 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo { if (tbrefTf.RefType != TableRefType.ManyToOne && tbrefTf.RefType != TableRefType.OneToOne) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {tbrefTypeName}.{pnv.Name} 解析错误,中间类 {tbmid.CsName}.{midTypePropsTbref.Name} 导航属性不是【ManyToOne】或【OneToOne】"); + nvref.Exception = new Exception(CoreStrings.ManyToMany_ParsingError_IntermediateClass_NotManyToOne_OneToOne(trytbTypeName, pnv.Name, tbmid.CsName, midTypePropsTbref.Name)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; } @@ -866,14 +866,14 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo } if (trycol != null && trycol.CsType.NullableTypeOrThis() != trytb.Primarys[a].CsType.NullableTypeOrThis()) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,{tbmid.CsName}.{trycol.CsName} 和 {trytb.CsName}.{trytb.Primarys[a].CsName} 类型不一致"); + nvref.Exception = new Exception(CoreStrings.ManyToMany_ParsingError_InconsistentType(trytbTypeName, pnv.Name, tbmid.CsName, trycol.CsName, trytb.CsName, trytb.Primarys[a].CsName)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; break; } if (trycol == null) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 在 {tbmid.CsName} 中没有找到对应的字段,如:{midTypePropsTrytb.Name}{findtrytbPkCsName}、{midTypePropsTrytb.Name}_{findtrytbPkCsName}"); + nvref.Exception = new Exception(CoreStrings.ManyToMany_NotFound_CorrespondingField(trytbTypeName, pnv.Name, tbmid.CsName, midTypePropsTrytb.Name, findtrytbPkCsName)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; break; @@ -906,14 +906,14 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo } if (trycol != null && trycol.CsType.NullableTypeOrThis() != tbref.Primarys[a].CsType.NullableTypeOrThis()) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,{tbmid.CsName}.{trycol.CsName} 和 {tbref.CsName}.{tbref.Primarys[a].CsName} 类型不一致"); + nvref.Exception = new Exception(CoreStrings.ManyToMany_ParsingError_InconsistentType(trytbTypeName, pnv.Name, tbmid.CsName, trycol.CsName, trytb.CsName, trytb.Primarys[a].CsName)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; break; } if (trycol == null) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 在 {tbmid.CsName} 中没有找到对应的字段,如:{midTypePropsTbref.Name}{findtbrefPkCsName}、{midTypePropsTbref.Name}_{findtbrefPkCsName}"); + nvref.Exception = new Exception(CoreStrings.ManyToMany_NotFound_CorrespondingField(trytbTypeName, pnv.Name, tbmid.CsName, midTypePropsTrytb.Name, findtbrefPkCsName)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; break; @@ -987,7 +987,7 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo { if (tbref.ColumnsByCs.TryGetValue(bi, out var trybindcol) == false) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 特性 [Navigate] 解析错误,在 {tbrefTypeName} 未找到属性:{bi}"); + nvref.Exception = new Exception(CoreStrings.Navigation_ParsingError_NotFound_Property(trytbTypeName, pnv.Name, tbrefTypeName, bi)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; break; @@ -1003,7 +1003,7 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo if (nvref.Exception == null && bindColumns.Any() && bindColumns.Count != trytb.Primarys.Length) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 特性 [Navigate] Bind 数目({bindColumns.Count}) 与 内部主键数目({trytb.Primarys.Length}) 不相同"); + nvref.Exception = new Exception(CoreStrings.Navigation_Bind_Number_Different(trytbTypeName, pnv.Name, bindColumns.Count, trytb.Primarys.Length)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; } @@ -1043,14 +1043,15 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo } if (trycol != null && trycol.CsType.NullableTypeOrThis() != trytb.Primarys[a].CsType.NullableTypeOrThis()) { - nvref.Exception = new Exception($"【OneToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,{trytb.CsName}.{trytb.Primarys[a].CsName} 和 {tbref.CsName}.{trycol.CsName} 类型不一致"); + nvref.Exception = new Exception(CoreStrings.OneToMany_ParsingError_InconsistentType(trytbTypeName, pnv.Name, trytb.CsName, trytb.Primarys[a].CsName, tbref.CsName, trycol.CsName)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; break; } if (trycol == null) { - nvref.Exception = new Exception($"【OneToMany】导航属性 {trytbTypeName}.{pnv.Name} 在 {tbref.CsName} 中没有找到对应的字段,如:{findtrytb}{findtrytbPkCsName}、{findtrytb}_{findtrytbPkCsName}" + (refprop == null ? "" : $"、{refprop.Name}{findtrytbPkCsName}、{refprop.Name}_{findtrytbPkCsName}。或者使用 [Navigate] 特性指定关系映射。")); + nvref.Exception = new Exception(CoreStrings.OneToMany_NotFound_CorrespondingField(trytbTypeName, pnv.Name, tbref.CsName, findtrytb, findtrytbPkCsName) + + (refprop == null ? "" : CoreStrings.OneToMany_UseNavigate(refprop.Name, findtrytbPkCsName))); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; break; @@ -1127,7 +1128,7 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo if (tbref == null) return; if (tbref.Primarys.Any() == false) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 解析错误,实体类型 {propTypeName} 缺少主键标识,[Column(IsPrimary = true)]"); + nvref.Exception = new Exception(CoreStrings.Navigation_ParsingError_EntityMissingPrimaryKey(trytbTypeName, pnv.Name, propTypeName)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; } @@ -1144,7 +1145,7 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo { if (trytb.ColumnsByCs.TryGetValue(bi, out var trybindcol) == false) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 特性 [Navigate] 解析错误,在 {trytbTypeName} 未找到属性:{bi}"); + nvref.Exception = new Exception(CoreStrings.Navigation_ParsingError_NotFound_Property(trytbTypeName, pnv.Name, trytbTypeName, bi)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; break; @@ -1156,7 +1157,7 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo if (nvref.Exception == null && bindColumns.Any() && bindColumns.Count != tbref.Primarys.Length) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 特性 [Navigate] Bind 数目({bindColumns.Count}) 与 外部主键数目({tbref.Primarys.Length}) 不相同"); + nvref.Exception = new Exception(CoreStrings.Navigation_Bind_Number_Different(trytbTypeName, pnv.Name, bindColumns.Count, tbref.Primarys.Length)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; } @@ -1211,14 +1212,14 @@ public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo } if (trycol != null && trycol.CsType.NullableTypeOrThis() != tbref.Primarys[a].CsType.NullableTypeOrThis()) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 解析错误,{trytb.CsName}.{trycol.CsName} 和 {tbref.CsName}.{tbref.Primarys[a].CsName} 类型不一致"); + nvref.Exception = new Exception(CoreStrings.Navigation_ParsingError_InconsistentType(trytbTypeName, pnv.Name, trytb.CsName, trycol.CsName, tbref.CsName, tbref.Primarys[a].CsName)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; break; } if (trycol == null) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 没有找到对应的字段,如:{pnv.Name}{findtbrefPkCsName}、{pnv.Name}_{findtbrefPkCsName}。或者使用 [Navigate] 特性指定关系映射。"); + nvref.Exception = new Exception(CoreStrings.Navigation_NotFound_CorrespondingField(trytbTypeName, pnv.Name, findtbrefPkCsName)); trytb.AddOrUpdateTableRef(pnv.Name, nvref); //if (isLazy) throw nvref.Exception; break; @@ -1793,7 +1794,7 @@ internal static void FillPropertyValue(object info, string memberAccessPath, obj var parmValue = Expression.Parameter(typeof(object), "value"); Expression exp = Expression.Convert(parmInfo, typeObj); foreach (var pro in memberAccessPath.Split('.')) - exp = Expression.PropertyOrField(exp, pro) ?? throw new Exception(string.Concat(exp.Type.FullName, " 没有定义属性 ", pro)); + exp = Expression.PropertyOrField(exp, pro) ?? throw new Exception(string.Concat(exp.Type.FullName, CoreStrings.NoProperty_Defined, pro)); var value2 = Expression.Call(MethodGetDataReaderValue, Expression.Constant(exp.Type), parmValue); var value3 = Expression.Convert(parmValue, typeValue); @@ -2261,7 +2262,7 @@ public static object GetDataReaderValue(Type type, object value) } catch (Exception ex) { - throw new ArgumentException($"ExpressionTree 转换类型错误,值({string.Concat(value)}),类型({value.GetType().FullName}),目标类型({type.FullName}),{ex.Message}"); + throw new ArgumentException(CoreStrings.ExpressionTree_Convert_Type_Error(string.Concat(value), value.GetType().FullName, type.FullName, ex.Message)); } } public static string GetCsName(string name) @@ -2359,7 +2360,7 @@ string LocalProcessBrackets(string locsql) var ltidx = ltidxStack.Pop(); var ltidx2 = ltidx; var sidx2 = sidx; - while(sidx < locsql.Length) + while (sidx < locsql.Length) { var chr2 = locsql[sidx]; if (chr2 == ')') diff --git a/FreeSql/Properties/CoreStrings.Designer.cs b/FreeSql/Properties/CoreStrings.Designer.cs new file mode 100644 index 000000000..342086681 --- /dev/null +++ b/FreeSql/Properties/CoreStrings.Designer.cs @@ -0,0 +1,977 @@ + +// + +using System; +using System.Reflection; +using System.Resources; +using System.Threading; + +namespace FreeSql +{ + /// + /// + /// String resources used in FreeSql exceptions, etc. + /// + /// + /// These strings are exposed publicly for use by database providers and extensions. + /// It is unusual for application code to need these strings. + /// + /// + public static class CoreStrings + { + private static readonly ResourceManager _resourceManager + = new ResourceManager("FreeSql.Properties.CoreStrings", typeof(CoreStrings).Assembly); + + /// + /// [Table(AsTable = "{asTable}")] 特性值格式错误 + /// + public static string AsTable_PropertyName_FormatError(object asTable) + => string.Format( + GetString("AsTable_PropertyName_FormatError", nameof(asTable)), + asTable); + + /// + /// [Table(AsTable = xx)] 设置的属性名 {atmGroupsValue} 不是 DateTime 类型 + /// + public static string AsTable_PropertyName_NotDateTime(object atmGroupsValue) + => string.Format( + GetString("AsTable_PropertyName_NotDateTime", nameof(atmGroupsValue)), + atmGroupsValue); + + /// + /// {name}: Failed to get resource {statistics} + /// + public static string Available_Failed_Get_Resource(object name, object statistics) + => string.Format( + GetString("Available_Failed_Get_Resource", nameof(name), nameof(statistics)), + name, statistics); + + /// + /// {name}: An exception needs to be thrown + /// + public static string Available_Thrown_Exception(object name) + => string.Format( + GetString("Available_Thrown_Exception", nameof(name)), + name); + + /// + /// 错误的表达式格式 {column} + /// + public static string Bad_Expression_Format(object column) + => string.Format( + GetString("Bad_Expression_Format", nameof(column)), + column); + + /// + /// Chunk 功能之前不可使用 Select + /// + public static string Before_Chunk_Cannot_Use_Select + => GetString("Before_Chunk_Cannot_Use_Select"); + + /// + /// 安全起见,请务必在事务开启之后,再使用 ForUpdate + /// + public static string Begin_Transaction_Then_ForUpdate + => GetString("Begin_Transaction_Then_ForUpdate"); + + /// + /// 不能为 null + /// + public static string Cannot_Be_NULL + => GetString("Cannot_Be_NULL"); + + /// + /// {name} 不能为 null + /// + public static string Cannot_Be_NULL_Name(object name) + => string.Format( + GetString("Cannot_Be_NULL_Name", nameof(name)), + name); + + /// + /// 无法匹配 {property} + /// + public static string Cannot_Match_Property(object property) + => string.Format( + GetString("Cannot_Match_Property", nameof(property)), + property); + + /// + /// {property} 无法解析为表达式树 + /// + public static string Cannot_Resolve_ExpressionTree(object property) + => string.Format( + GetString("Cannot_Resolve_ExpressionTree", nameof(property)), + property); + + /// + /// 参数 masterConnectionString 不可为空,请检查 UseConnectionString + /// + public static string Check_UseConnectionString + => GetString("Check_UseConnectionString"); + + /// + /// 提交 + /// + public static string Commit + => GetString("Commit"); + + /// + /// 连接失败,准备切换其他可用服务器 + /// + public static string Connection_Failed_Switch_Servers + => GetString("Connection_Failed_Switch_Servers"); + + /// + /// 自定义表达式解析错误:类型 {exp3MethodDeclaringType} 需要定义 static ThreadLocal<ExpressionCallContext> 字段、字段、字段(重要三次提醒) + /// + public static string Custom_Expression_ParsingError(object exp3MethodDeclaringType) + => string.Format( + GetString("Custom_Expression_ParsingError", nameof(exp3MethodDeclaringType)), + exp3MethodDeclaringType); + + /// + /// Custom { 反射信息 }不能为空,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } + /// + public static string Custom_Reflection_IsNotNull + => GetString("Custom_Reflection_IsNotNull"); + + /// + /// Custom { 静态方法名 }不能为空,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } + /// + public static string Custom_StaticMethodName_IsNotNull + => GetString("Custom_StaticMethodName_IsNotNull"); + + /// + /// Custom 对应的{{ 静态方法名 }}:{fiValueCustomArray} 未设置 [DynamicFilterCustomAttribute] 特性 + /// + public static string Custom_StaticMethodName_NotSet_DynamicFilterCustom(object fiValueCustomArray) + => string.Format( + GetString("Custom_StaticMethodName_NotSet_DynamicFilterCustom", nameof(fiValueCustomArray)), + fiValueCustomArray); + + /// + /// Custom 要求 Field 应该空格分割,并且长度为 2,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } + /// + public static string CustomFieldSeparatedBySpaces + => GetString("CustomFieldSeparatedBySpaces"); + + /// + /// 操作的数据类型({dataDisplayCsharp}) 与 AsType({tableTypeDisplayCsharp}) 不一致,请检查。 + /// + public static string DataType_AsType_Inconsistent(object dataDisplayCsharp, object tableTypeDisplayCsharp) + => string.Format( + GetString("DataType_AsType_Inconsistent", nameof(dataDisplayCsharp), nameof(tableTypeDisplayCsharp)), + dataDisplayCsharp, tableTypeDisplayCsharp); + + /// + /// DateRange 要求 Value 应该逗号分割,并且长度为 2 + /// + public static string DateRange_Comma_Separateda_By2Char + => GetString("DateRange_Comma_Separateda_By2Char"); + + /// + /// DateRange 要求 Value[1] 格式必须为:yyyy、yyyy-MM、yyyy-MM-dd、yyyy-MM-dd HH、yyyy、yyyy-MM-dd HH:mm + /// + public static string DateRange_DateFormat_yyyy + => GetString("DateRange_DateFormat_yyyy"); + + /// + /// 记录可能不存在,或者【行级乐观锁】版本过旧,更新数量{sourceCount},影响的行数{affrows}。 + /// + public static string DbUpdateVersionException_RowLevelOptimisticLock(object sourceCount, object affrows) + => string.Format( + GetString("DbUpdateVersionException_RowLevelOptimisticLock", nameof(sourceCount), nameof(affrows)), + sourceCount, affrows); + + /// + /// SlaveConnectionString 数量与 SlaveWeights 不相同 + /// + public static string Different_Number_SlaveConnectionString_SlaveWeights + => GetString("Different_Number_SlaveConnectionString_SlaveWeights"); + + /// + /// ColumnAttribute.Name {colattrName} 重复存在,请检查(注意:不区分大小写) + /// + public static string Duplicate_ColumnAttribute(object colattrName) + => string.Format( + GetString("Duplicate_ColumnAttribute", nameof(colattrName)), + colattrName); + + /// + /// 属性名 {pName} 重复存在,请检查(注意:不区分大小写) + /// + public static string Duplicate_PropertyName(object pName) + => string.Format( + GetString("Duplicate_PropertyName", nameof(pName)), + pName); + + /// + /// {function} 功能要求实体类 {tableCsName} 必须有主键 + /// + public static string Entity_Must_Primary_Key(object function, object tableCsName) + => string.Format( + GetString("Entity_Must_Primary_Key", nameof(function), nameof(tableCsName)), + function, tableCsName); + + /// + /// {tbTypeFullName} 是父子关系,但是 MySql 8.0 以下版本中不支持组合多主键 + /// + public static string Entity_MySQL_VersionsBelow8_NotSupport_Multiple_PrimaryKeys(object tbTypeFullName) + => string.Format( + GetString("Entity_MySQL_VersionsBelow8_NotSupport_Multiple_PrimaryKeys", nameof(tbTypeFullName)), + tbTypeFullName); + + /// + /// {tbTypeFullName} 不是父子关系,无法使用该功能 + /// + public static string Entity_NotParentChild_Relationship(object tbTypeFullName) + => string.Format( + GetString("Entity_NotParentChild_Relationship", nameof(tbTypeFullName)), + tbTypeFullName); + + /// + /// 这个特别的子查询不能解析 + /// + public static string EspeciallySubquery_Cannot_Parsing + => GetString("EspeciallySubquery_Cannot_Parsing"); + + /// + /// 表达式错误,它的顶级对象不是 ParameterExpression:{exp} + /// + public static string Expression_Error_Use_ParameterExpression(object exp) + => string.Format( + GetString("Expression_Error_Use_ParameterExpression", nameof(exp)), + exp); + + /// + /// 表达式错误,它不是连续的 MemberAccess 类型:{exp} + /// + public static string Expression_Error_Use_Successive_MemberAccess_Type(object exp) + => string.Format( + GetString("Expression_Error_Use_Successive_MemberAccess_Type", nameof(exp)), + exp); + + /// + /// ExpressionTree 转换类型错误,值({value}),类型({valueTypeFullName}),目标类型({typeFullName}),{exMessage} + /// + public static string ExpressionTree_Convert_Type_Error(object value, object valueTypeFullName, object typeFullName, object exMessage) + => string.Format( + GetString("ExpressionTree_Convert_Type_Error", nameof(value), nameof(valueTypeFullName), nameof(typeFullName), nameof(exMessage)), + value, valueTypeFullName, typeFullName, exMessage); + + /// + /// 未能解析分表字段值 {sqlWhere} + /// + public static string Failed_SubTable_FieldValue(object sqlWhere) + => string.Format( + GetString("Failed_SubTable_FieldValue", nameof(sqlWhere)), + sqlWhere); + + /// + /// AsTable 未实现的功能 {asTable} + /// + public static string Functions_AsTable_NotImplemented(object asTable) + => string.Format( + GetString("Functions_AsTable_NotImplemented", nameof(asTable)), + asTable); + + /// + /// GBase 暂时不支持逗号以外的分割符 + /// + public static string GBase_NotSupport_OtherThanCommas + => GetString("GBase_NotSupport_OtherThanCommas"); + + /// + /// tableName:{tableName} 生成了相同的分表名 + /// + public static string Generated_Same_SubTable(object tableName) + => string.Format( + GetString("Generated_Same_SubTable", nameof(tableName)), + tableName); + + /// + /// GetPrimarys 传递的参数 "{primary}" 不正确,它不属于字典数据的键名 + /// + public static string GetPrimarys_ParameterError_IsNotDictKey (object primary) + => string.Format( + GetString("GetPrimarys_ParameterError_IsNotDictKey ", nameof(primary)), + primary); + + /// + /// 已经指定了 {first},不能再指定 {second} + /// + public static string Has_Specified_Cannot_Specified_Second(object first, object second) + => string.Format( + GetString("Has_Specified_Cannot_Specified_Second", nameof(first), nameof(second)), + first, second); + + /// + /// {tb2DbName}.{mp2MemberName} 被忽略,请检查 IsIgnore 设置,确认 get/set 为 public + /// + public static string Ignored_Check_Confirm_PublicGetSet(object tb2DbName, object mp2MemberName) + => string.Format( + GetString("Ignored_Check_Confirm_PublicGetSet", nameof(tb2DbName), nameof(mp2MemberName)), + tb2DbName, mp2MemberName); + + /// + /// Include 参数类型错误 + /// + public static string Include_ParameterType_Error + => GetString("Include_ParameterType_Error"); + + /// + /// Include 参数类型错误,集合属性请使用 IncludeMany + /// + public static string Include_ParameterType_Error_Use_IncludeMany + => GetString("Include_ParameterType_Error_Use_IncludeMany"); + + /// + /// Include 参数类型错误,表达式类型应该为 MemberAccess + /// + public static string Include_ParameterType_Error_Use_MemberAccess + => GetString("Include_ParameterType_Error_Use_MemberAccess"); + + /// + /// IncludeMany 类型 {tbTypeDisplayCsharp} 的属性 {collMemMemberName} 不是有效的导航属性,提示:IsIgnore = true 不会成为导航属性 + /// + public static string IncludeMany_NotValid_Navigation(object tbTypeDisplayCsharp, object collMemMemberName) + => string.Format( + GetString("IncludeMany_NotValid_Navigation", nameof(tbTypeDisplayCsharp), nameof(collMemMemberName)), + tbTypeDisplayCsharp, collMemMemberName); + + /// + /// IncludeMany {navigateSelector} 参数错误,Select 只可以使用一个参数的方法,正确格式:.Select(t =>new TNavigate {{}}) + /// + public static string IncludeMany_ParameterError_OnlyUseOneParameter(object navigateSelector) + => string.Format( + GetString("IncludeMany_ParameterError_OnlyUseOneParameter", nameof(navigateSelector)), + navigateSelector); + + /// + /// IncludeMany {navigateSelector} 参数错误,Select lambda参数返回值必须和 {collMemElementType} 类型一致 + /// + public static string IncludeMany_ParameterError_Select_ReturnConsistentType(object navigateSelector, object collMemElementType) + => string.Format( + GetString("IncludeMany_ParameterError_Select_ReturnConsistentType", nameof(navigateSelector), nameof(collMemElementType)), + navigateSelector, collMemElementType); + + /// + /// IncludeMany 参数1 类型错误,表达式类型应该为 MemberAccess + /// + public static string IncludeMany_ParameterType_Error_Use_MemberAccess + => GetString("IncludeMany_ParameterType_Error_Use_MemberAccess"); + + /// + /// IncludeMany {navigateSelector} 参数类型错误,正确格式: a.collections.Take(1).Where(c =>c.aid == a.id).Select(a=> new TNavigate{{}}) + /// + public static string IncludeMany_ParameterTypeError(object navigateSelector) + => string.Format( + GetString("IncludeMany_ParameterTypeError", nameof(navigateSelector)), + navigateSelector); + + /// + /// ISelect.InsertInto() 未选择属性: {displayCsharp} + /// + public static string InsertInto_No_Property_Selected(object displayCsharp) + => string.Format( + GetString("InsertInto_No_Property_Selected", nameof(displayCsharp)), + displayCsharp); + + /// + /// ISelect.InsertInto() 类型错误: {displayCsharp} + /// + public static string InsertInto_TypeError(object displayCsharp) + => string.Format( + GetString("InsertInto_TypeError", nameof(displayCsharp)), + displayCsharp); + + /// + /// InsertOrUpdate 功能执行 merge into 要求实体类 {CsName} 必须有主键 + /// + public static string InsertOrUpdate_Must_Primary_Key(object CsName) + => string.Format( + GetString("InsertOrUpdate_Must_Primary_Key", nameof(CsName)), + CsName); + + /// + /// InsertOrUpdate<>的泛型参数 不支持 {typeofT1},请传递您的实体类 + /// + public static string InsertOrUpdate_NotSuport_Generic_UseEntity(object typeofT1) + => string.Format( + GetString("InsertOrUpdate_NotSuport_Generic_UseEntity", nameof(typeofT1)), + typeofT1); + + /// + /// 【延时加载】功能需要安装 FreeSql.Extensions.LazyLoading.dll,可前往 nuget 下载 + /// + public static string Install_FreeSql_Extensions_LazyLoading + => GetString("Install_FreeSql_Extensions_LazyLoading"); + + /// + /// 【延时加载】{trytbTypeName} 编译错误:{exMessage}\r\n\r\n{cscode} + /// + public static string LazyLoading_CompilationError(object trytbTypeName, object exMessage, object cscode) + => string.Format( + GetString("LazyLoading_CompilationError", nameof(trytbTypeName), nameof(exMessage), nameof(cscode)), + trytbTypeName, exMessage, cscode); + + /// + /// 【延时加载】实体类型 {trytbTypeName} 必须声明为 public + /// + public static string LazyLoading_EntityMustDeclarePublic(object trytbTypeName) + => string.Format( + GetString("LazyLoading_EntityMustDeclarePublic", nameof(trytbTypeName)), + trytbTypeName); + + /// + /// ManyToMany 导航属性 .AsSelect() 暂时不可用于 Sum/Avg/Max/Min/First/ToOne/ToList 方法 + /// + public static string ManyToMany_AsSelect_NotSupport_Sum_Avg_etc + => GetString("ManyToMany_AsSelect_NotSupport_Sum_Avg_etc"); + + /// + /// 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 在 {tbmidCsName} 中没有找到对应的字段,如:{midTypePropsTrytbName}{findtrytbPkCsName}、{midTypePropsTrytbName}_{findtrytbPkCsName} + /// + public static string ManyToMany_NotFound_CorrespondingField(object trytbTypeName, object pnvName, object tbmidCsName, object midTypePropsTrytbName, object findtrytbPkCsName) + => string.Format( + GetString("ManyToMany_NotFound_CorrespondingField", nameof(trytbTypeName), nameof(pnvName), nameof(tbmidCsName), nameof(midTypePropsTrytbName), nameof(findtrytbPkCsName)), + trytbTypeName, pnvName, tbmidCsName, midTypePropsTrytbName, findtrytbPkCsName); + + /// + /// 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {tbrefTypeName} 缺少主键标识,[Column(IsPrimary = true)] + /// + public static string ManyToMany_ParsingError_EntityMissing_PrimaryKey(object trytbTypeName, object pnvName, object tbrefTypeName) + => string.Format( + GetString("ManyToMany_ParsingError_EntityMissing_PrimaryKey", nameof(trytbTypeName), nameof(pnvName), nameof(tbrefTypeName)), + trytbTypeName, pnvName, tbrefTypeName); + + /// + /// 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {tbrefTypeName} 必须存在对应的 [Navigate(ManyToMany = x)] 集合属性 + /// + public static string ManyToMany_ParsingError_EntityMustHas_NavigateCollection(object trytbTypeName, object pnvName, object tbrefTypeName) + => string.Format( + GetString("ManyToMany_ParsingError_EntityMustHas_NavigateCollection", nameof(trytbTypeName), nameof(pnvName), nameof(tbrefTypeName)), + trytbTypeName, pnvName, tbrefTypeName); + + /// + /// 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,{tbmidCsName}.{trycolCsName} 和 {trytbCsName}.{trytbPrimarysCsName} 类型不一致 + /// + public static string ManyToMany_ParsingError_InconsistentType(object trytbTypeName, object pnvName, object tbmidCsName, object trycolCsName, object trytbCsName, object trytbPrimarysCsName) + => string.Format( + GetString("ManyToMany_ParsingError_InconsistentType", nameof(trytbTypeName), nameof(pnvName), nameof(tbmidCsName), nameof(trycolCsName), nameof(trytbCsName), nameof(trytbPrimarysCsName)), + trytbTypeName, pnvName, tbmidCsName, trycolCsName, trytbCsName, trytbPrimarysCsName); + + /// + /// 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,中间类 {tbmidCsName}.{midTypePropsTrytbName} 错误:{exMessage} + /// + public static string ManyToMany_ParsingError_IntermediateClass_ErrorMessage(object trytbTypeName, object pnvName, object tbmidCsName, object midTypePropsTrytbName, object exMessage) + => string.Format( + GetString("ManyToMany_ParsingError_IntermediateClass_ErrorMessage", nameof(trytbTypeName), nameof(pnvName), nameof(tbmidCsName), nameof(midTypePropsTrytbName), nameof(exMessage)), + trytbTypeName, pnvName, tbmidCsName, midTypePropsTrytbName, exMessage); + + /// + /// 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,中间类 {tbmidCsName}.{midTypePropsTrytbName} 导航属性不是【ManyToOne】或【OneToOne】 + /// + public static string ManyToMany_ParsingError_IntermediateClass_NotManyToOne_OneToOne(object trytbTypeName, object pnvName, object tbmidCsName, object midTypePropsTrytbName) + => string.Format( + GetString("ManyToMany_ParsingError_IntermediateClass_NotManyToOne_OneToOne", nameof(trytbTypeName), nameof(pnvName), nameof(tbmidCsName), nameof(midTypePropsTrytbName)), + trytbTypeName, pnvName, tbmidCsName, midTypePropsTrytbName); + + /// + /// 映射异常:{name} 没有一个属性名相同 + /// + public static string Mapping_Exception_HasNo_SamePropertyName(object name) + => string.Format( + GetString("Mapping_Exception_HasNo_SamePropertyName", nameof(name)), + name); + + /// + /// Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决 + /// + public static string MasterPool_IsNull_UseTransaction + => GetString("MasterPool_IsNull_UseTransaction"); + + /// + /// 缺少 FreeSql 数据库实现包:FreeSql.Provider.{Provider}.dll,可前往 nuget 下载 + /// + public static string Missing_FreeSqlProvider_Package(object Provider) + => string.Format( + GetString("Missing_FreeSqlProvider_Package", nameof(Provider)), + Provider); + + /// + /// 缺少 FreeSql 数据库实现包:{dll},可前往 nuget 下载;如果存在 {dll} 依然报错(原因是环境问题导致反射不到类型),请在 UseConnectionString/UseConnectionFactory 第三个参数手工传入 typeof({providerType}) + /// + public static string Missing_FreeSqlProvider_Package_Reason(object dll, object providerType) + => string.Format( + GetString("Missing_FreeSqlProvider_Package_Reason", nameof(dll), nameof(providerType)), + dll, providerType); + + /// + /// 导航属性 {trytbTypeName}.{pnvName} 特性 [Navigate] Bind 数目({bindColumnsCount}) 与 外部主键数目({tbrefPrimarysLength}) 不相同 + /// + public static string Navigation_Bind_Number_Different(object trytbTypeName, object pnvName, object bindColumnsCount, object tbrefPrimarysLength) + => string.Format( + GetString("Navigation_Bind_Number_Different", nameof(trytbTypeName), nameof(pnvName), nameof(bindColumnsCount), nameof(tbrefPrimarysLength)), + trytbTypeName, pnvName, bindColumnsCount, tbrefPrimarysLength); + + /// + /// {tb2DbName}.{mp2MemberName} 导航属性集合忘了 .AsSelect() 吗?如果在 ToList(a => a.{mp2MemberName}) 中使用,请移步参考 IncludeMany 文档。 + /// + public static string Navigation_Missing_AsSelect(object tb2DbName, object mp2MemberName) + => string.Format( + GetString("Navigation_Missing_AsSelect", nameof(tb2DbName), nameof(mp2MemberName)), + tb2DbName, mp2MemberName); + + /// + /// 【导航属性】{trytbTypeDisplayCsharp}.{pName} 缺少 set 属性 + /// + public static string Navigation_Missing_SetProperty(object trytbTypeDisplayCsharp, object pName) + => string.Format( + GetString("Navigation_Missing_SetProperty", nameof(trytbTypeDisplayCsharp), nameof(pName)), + trytbTypeDisplayCsharp, pName); + + /// + /// 导航属性 {trytbTypeName}.{pnvName} 没有找到对应的字段,如:{pnvName}{findtbrefPkCsName}、{pnvName}_{findtbrefPkCsName}。或者使用 [Navigate] 特性指定关系映射。 + /// + public static string Navigation_NotFound_CorrespondingField(object trytbTypeName, object pnvName, object findtbrefPkCsName) + => string.Format( + GetString("Navigation_NotFound_CorrespondingField", nameof(trytbTypeName), nameof(pnvName), nameof(findtbrefPkCsName)), + trytbTypeName, pnvName, findtbrefPkCsName); + + /// + /// 导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {trytcTypeName} 缺少主键标识,[Column(IsPrimary = true)] + /// + public static string Navigation_ParsingError_EntityMissingPrimaryKey(object trytbTypeName, object pnvName, object trytcTypeName) + => string.Format( + GetString("Navigation_ParsingError_EntityMissingPrimaryKey", nameof(trytbTypeName), nameof(pnvName), nameof(trytcTypeName)), + trytbTypeName, pnvName, trytcTypeName); + + /// + /// 导航属性 {trytbTypeName}.{pnvName} 解析错误,{trytbCsName}.{trycolCsName} 和 {tbrefCsName}.{tbrefPrimarysCsName} 类型不一致 + /// + public static string Navigation_ParsingError_InconsistentType(object trytbTypeName, object pnvName, object trytbCsName, object trycolCsName, object tbrefCsName, object tbrefPrimarysCsName) + => string.Format( + GetString("Navigation_ParsingError_InconsistentType", nameof(trytbTypeName), nameof(pnvName), nameof(trytbCsName), nameof(trycolCsName), nameof(tbrefCsName), nameof(tbrefPrimarysCsName)), + trytbTypeName, pnvName, trytbCsName, trycolCsName, tbrefCsName, tbrefPrimarysCsName); + + /// + /// 导航属性 {trytbTypeName}.{pnvName} 特性 [Navigate] 解析错误,在 {tbrefTypeName} 未找到属性:{bi} + /// + public static string Navigation_ParsingError_NotFound_Property(object trytbTypeName, object pnvName, object tbrefTypeName, object bi) + => string.Format( + GetString("Navigation_ParsingError_NotFound_Property", nameof(trytbTypeName), nameof(pnvName), nameof(tbrefTypeName), nameof(bi)), + trytbTypeName, pnvName, tbrefTypeName, bi); + + /// + /// {tableTypeDisplayCsharp} 没有定义主键,无法使用 SetSource,请尝试 SetDto + /// + public static string NoPrimaryKey_UseSetDto(object tableTypeDisplayCsharp) + => string.Format( + GetString("NoPrimaryKey_UseSetDto", nameof(tableTypeDisplayCsharp)), + tableTypeDisplayCsharp); + + /// + /// 没有定义属性 + /// + public static string NoProperty_Defined + => GetString("NoProperty_Defined"); + + /// + /// 未实现 + /// + public static string Not_Implemented + => GetString("Not_Implemented"); + + /// + /// 未实现函数表达式 {exp} 解析 + /// + public static string Not_Implemented_Expression(object exp) + => string.Format( + GetString("Not_Implemented_Expression", nameof(exp)), + exp); + + /// + /// 未实现函数表达式 {exp} 解析,参数 {expArguments} 必须为常量 + /// + public static string Not_Implemented_Expression_ParameterUseConstant(object exp, object expArguments) + => string.Format( + GetString("Not_Implemented_Expression_ParameterUseConstant", nameof(exp), nameof(expArguments)), + exp, expArguments); + + /// + /// 未实现函数表达式 {exp} 解析,如果正在操作导航属性集合,请使用 .AsSelect().{exp3MethodName}({exp3ArgumentsCount}) + /// + public static string Not_Implemented_Expression_UseAsSelect(object exp, object exp3MethodName, object exp3ArgumentsCount) + => string.Format( + GetString("Not_Implemented_Expression_UseAsSelect", nameof(exp), nameof(exp3MethodName), nameof(exp3ArgumentsCount)), + exp, exp3MethodName, exp3ArgumentsCount); + + /// + /// 未实现 MemberAccess 下的 Constant + /// + public static string Not_Implemented_MemberAcess_Constant + => GetString("Not_Implemented_MemberAcess_Constant"); + + /// + /// 未实现 {name} + /// + public static string Not_Implemented_Name(object name) + => string.Format( + GetString("Not_Implemented_Name", nameof(name)), + name); + + /// + /// 不支持 + /// + public static string Not_Support + => GetString("Not_Support"); + + /// + /// {dataType} 不支持 OrderByRandom 随机排序 + /// + public static string Not_Support_OrderByRandom(object dataType) + => string.Format( + GetString("Not_Support_OrderByRandom", nameof(dataType)), + dataType); + + /// + /// {property} 不是有效的导航属性 + /// + public static string Not_Valid_Navigation_Property(object property) + => string.Format( + GetString("Not_Valid_Navigation_Property", nameof(property)), + property); + + /// + /// {dbName} 找不到列 {memberName} + /// + public static string NotFound_Column(object dbName, object memberName) + => string.Format( + GetString("NotFound_Column", nameof(dbName), nameof(memberName)), + dbName, memberName); + + /// + /// 找不到 {CsName} 对应的列 + /// + public static string NotFound_CsName_Column(object CsName) + => string.Format( + GetString("NotFound_CsName_Column", nameof(CsName)), + CsName); + + /// + /// 找不到属性:{memberName} + /// + public static string NotFound_Property(object memberName) + => string.Format( + GetString("NotFound_Property", nameof(memberName)), + memberName); + + /// + /// 找不到属性名 {proto} + /// + public static string NotFound_PropertyName(object proto) + => string.Format( + GetString("NotFound_PropertyName", nameof(proto)), + proto); + + /// + /// Custom 找不到对应的{{ 反射信息 }}:{fiValueCustomArray} + /// + public static string NotFound_Reflection(object fiValueCustomArray) + => string.Format( + GetString("NotFound_Reflection", nameof(fiValueCustomArray)), + fiValueCustomArray); + + /// + /// Custom 找不到对应的{{ 静态方法名 }}:{fiValueCustomArray} + /// + public static string NotFound_Static_MethodName(object fiValueCustomArray) + => string.Format( + GetString("NotFound_Static_MethodName", nameof(fiValueCustomArray)), + fiValueCustomArray); + + /// + /// [Table(AsTable = xx)] 设置的属性名 {atmGroupsValue} 不存在 + /// + public static string NotFound_Table_Property_AsTable(object atmGroupsValue) + => string.Format( + GetString("NotFound_Table_Property_AsTable", nameof(atmGroupsValue)), + atmGroupsValue); + + /// + /// 未指定 UseConnectionString 或者 UseConnectionFactory + /// + public static string NotSpecified_UseConnectionString_UseConnectionFactory + => GetString("NotSpecified_UseConnectionString_UseConnectionFactory"); + + /// + /// 【{policyName}】ObjectPool.{GetName}() timeout {totalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081 + /// + public static string ObjectPool_Get_Timeout(object policyName, object GetName, object totalSeconds) + => string.Format( + GetString("ObjectPool_Get_Timeout", nameof(policyName), nameof(GetName), nameof(totalSeconds)), + policyName, GetName, totalSeconds); + + /// + /// 【{policyName}】ObjectPool.GetAsync() The queue is too long. Policy.AsyncGetCapacity = {asyncGetCapacity} + /// + public static string ObjectPool_GetAsync_Queue_Long(object policyName, object asyncGetCapacity) + => string.Format( + GetString("ObjectPool_GetAsync_Queue_Long", nameof(policyName), nameof(asyncGetCapacity)), + policyName, asyncGetCapacity); + + /// + /// 【OneToMany】导航属性 {trytbTypeName}.{pnvName} 在 {tbrefCsName} 中没有找到对应的字段,如:{findtrytb}{findtrytbPkCsName}、{findtrytb}_{findtrytbPkCsName} + /// + public static string OneToMany_NotFound_CorrespondingField(object trytbTypeName, object pnvName, object tbrefCsName, object findtrytb, object findtrytbPkCsName) + => string.Format( + GetString("OneToMany_NotFound_CorrespondingField", nameof(trytbTypeName), nameof(pnvName), nameof(tbrefCsName), nameof(findtrytb), nameof(findtrytbPkCsName)), + trytbTypeName, pnvName, tbrefCsName, findtrytb, findtrytbPkCsName); + + /// + /// 【OneToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,{trytbCsName}.{trytbPrimarysCsName} 和 {tbrefCsName}.{trycolCsName} 类型不一致 + /// + public static string OneToMany_ParsingError_InconsistentType(object trytbTypeName, object pnvName, object trytbCsName, object trytbPrimarysCsName, object tbrefCsName, object trycolCsName) + => string.Format( + GetString("OneToMany_ParsingError_InconsistentType", nameof(trytbTypeName), nameof(pnvName), nameof(trytbCsName), nameof(trytbPrimarysCsName), nameof(tbrefCsName), nameof(trycolCsName)), + trytbTypeName, pnvName, trytbCsName, trytbPrimarysCsName, tbrefCsName, trycolCsName); + + /// + /// 、{refpropName}{findtrytbPkCsName}、{refpropName}_{findtrytbPkCsName}。或者使用 [Navigate] 特性指定关系映射。 + /// + public static string OneToMany_UseNavigate(object refpropName, object findtrytbPkCsName) + => string.Format( + GetString("OneToMany_UseNavigate", nameof(refpropName), nameof(findtrytbPkCsName)), + refpropName, findtrytbPkCsName); + + /// + /// 参数 field 未指定 + /// + public static string Parameter_Field_NotSpecified + => GetString("Parameter_Field_NotSpecified"); + + /// + /// {property} 参数错误,它不是集合属性,必须为 IList<T> 或者 ICollection<T> + /// + public static string ParameterError_NotValid_Collection(object property) + => string.Format( + GetString("ParameterError_NotValid_Collection", nameof(property)), + property); + + /// + /// {property} 参数错误,它不是有效的导航属性 + /// + public static string ParameterError_NotValid_Navigation(object property) + => string.Format( + GetString("ParameterError_NotValid_Navigation", nameof(property)), + property); + + /// + /// {where} 参数错误,{keyval} 不是有效的属性名,在实体类 {reftbTypeDisplayCsharp} 无法找到 + /// + public static string ParameterError_NotValid_PropertyName(object where, object keyval, object reftbTypeDisplayCsharp) + => string.Format( + GetString("ParameterError_NotValid_PropertyName", nameof(where), nameof(keyval), nameof(reftbTypeDisplayCsharp)), + where, keyval, reftbTypeDisplayCsharp); + + /// + /// {property} 参数错误,格式 "TopicId=Id,多组使用逗号连接" + /// + public static string ParameterError_NotValid_UseCommas(object property) + => string.Format( + GetString("ParameterError_NotValid_UseCommas", nameof(property)), + property); + + /// + /// 解析失败 {callExpMethodName} {message} + /// + public static string Parsing_Failed(object callExpMethodName, object message) + => string.Format( + GetString("Parsing_Failed", nameof(callExpMethodName), nameof(message)), + callExpMethodName, message); + + /// + /// 【{policyName}】The ObjectPool has been disposed, see: https://github.com/dotnetcore/FreeSql/discussions/1079 + /// + public static string Policy_ObjectPool_Dispose(object policyName) + => string.Format( + GetString("Policy_ObjectPool_Dispose", nameof(policyName)), + policyName); + + /// + /// 【{policyName}】状态不可用,等待后台检查程序恢复方可使用。{UnavailableExceptionMessage} + /// + public static string Policy_Status_NotAvailable(object policyName, object UnavailableExceptionMessage) + => string.Format( + GetString("Policy_Status_NotAvailable", nameof(policyName), nameof(UnavailableExceptionMessage)), + policyName, UnavailableExceptionMessage); + + /// + /// 属性{trytbVersionColumnCsName} 被标注为行锁(乐观锁)(IsVersion),但其必须为数字类型 或者 byte[],并且不可为 Nullable + /// + public static string Properties_AsRowLock_Must_Numeric_Byte(object trytbVersionColumnCsName) + => string.Format( + GetString("Properties_AsRowLock_Must_Numeric_Byte", nameof(trytbVersionColumnCsName)), + trytbVersionColumnCsName); + + /// + /// properties 参数不能为空 + /// + public static string Properties_Cannot_Null + => GetString("Properties_Cannot_Null"); + + /// + /// {property} 属性名无法找到 + /// + public static string Property_Cannot_Find(object property) + => string.Format( + GetString("Property_Cannot_Find", nameof(property)), + property); + + /// + /// Range 要求 Value 应该逗号分割,并且长度为 2 + /// + public static string Range_Comma_Separateda_By2Char + => GetString("Range_Comma_Separateda_By2Char"); + + /// + /// 回滚 + /// + public static string RollBack + => GetString("RollBack"); + + /// + /// 运行时错误,反射获取 IncludeMany 方法失败 + /// + public static string RunTimeError_Reflection_IncludeMany + => GetString("RunTimeError_Reflection_IncludeMany"); + + /// + /// {qoteSql} is NULL,除非设置特性 [Column(IsNullable = false)] + /// + public static string Set_Column_IsNullable_False(object qoteSql) + => string.Format( + GetString("Set_Column_IsNullable_False", nameof(qoteSql)), + qoteSql); + + /// + /// 分表字段值 "{dt}" 不能小于 "{beginTime} " + /// + public static string SubTableFieldValue_CannotLessThen(object dt, object beginTime) + => string.Format( + GetString("SubTableFieldValue_CannotLessThen", nameof(dt), nameof(beginTime)), + dt, beginTime); + + /// + /// 分表字段值不能为 null + /// + public static string SubTableFieldValue_IsNotNull + => GetString("SubTableFieldValue_IsNotNull"); + + /// + /// 分表字段值 "{columnValue}" 不能转化成 DateTime + /// + public static string SubTableFieldValue_NotConvertDateTime(object columnValue) + => string.Format( + GetString("SubTableFieldValue_NotConvertDateTime", nameof(columnValue)), + columnValue); + + /// + /// 分表字段值 "{dt}" 未匹配到分表名 + /// + public static string SubTableFieldValue_NotMatchTable(object dt) + => string.Format( + GetString("SubTableFieldValue_NotMatchTable", nameof(dt)), + dt); + + /// + /// T2 类型错误 + /// + public static string T2_Type_Error + => GetString("T2_Type_Error"); + + /// + /// tableName 格式错误,示例:“log_{yyyyMMdd}” + /// + public static string TableName_Format_Error(object yyyyMMdd) + => string.Format( + GetString("TableName_Format_Error", nameof(yyyyMMdd)), + yyyyMMdd); + + /// + /// {Type}.AsType 参数错误,请传入正确的实体类型 + /// + public static string Type_AsType_Parameter_Error(object Type) + => string.Format( + GetString("Type_AsType_Parameter_Error", nameof(Type)), + Type); + + /// + /// {thatFullName} 类型无法访问构造函数 + /// + public static string Type_Cannot_Access_Constructor(object thatFullName) + => string.Format( + GetString("Type_Cannot_Access_Constructor", nameof(thatFullName)), + thatFullName); + + /// + /// {name} 类型错误 + /// + public static string Type_Error_Name(object name) + => string.Format( + GetString("Type_Error_Name", nameof(name)), + name); + + /// + /// {Type}.AsType 参数不支持指定为 object + /// + public static string TypeAsType_NotSupport_Object(object Type) + => string.Format( + GetString("TypeAsType_NotSupport_Object", nameof(Type)), + Type); + + /// + /// 类型 {typeofFullName} 错误,不能使用 IncludeMany + /// + public static string TypeError_CannotUse_IncludeMany(object typeofFullName) + => string.Format( + GetString("TypeError_CannotUse_IncludeMany", nameof(typeofFullName)), + typeofFullName); + + /// + /// 无法解析表达式:{exp} + /// + public static string Unable_Parse_Expression(object exp) + => string.Format( + GetString("Unable_Parse_Expression", nameof(exp)), + exp); + + /// + /// 无法解析表达式方法 {exp3tmpCallMethodName} + /// + public static string Unable_Parse_ExpressionMethod(object exp3tmpCallMethodName) + => string.Format( + GetString("Unable_Parse_ExpressionMethod", nameof(exp3tmpCallMethodName)), + exp3tmpCallMethodName); + + /// + /// 请使用 fsql.InsertDict(dict) 方法插入字典数据 + /// + public static string Use_InsertDict_Method + => GetString("Use_InsertDict_Method"); + + private static string GetString(string name, params string[] formatterNames) + { + var value = _resourceManager.GetString(name); + for (var i = 0; i < formatterNames.Length; i++) + { + value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}"); + } + + return value; + } + } +} + diff --git a/FreeSql/Properties/CoreStrings.Designer.tt b/FreeSql/Properties/CoreStrings.Designer.tt new file mode 100644 index 000000000..1b17aead8 --- /dev/null +++ b/FreeSql/Properties/CoreStrings.Designer.tt @@ -0,0 +1,5 @@ +<# + Session["ResourceFile"] = "CoreStrings.resx"; + Session["AccessModifier"] = "public"; +#> +<#@ include file="Resources.tt" #> \ No newline at end of file diff --git a/FreeSql/Properties/CoreStrings.en-US.resx b/FreeSql/Properties/CoreStrings.en-US.resx new file mode 100644 index 000000000..9d3cd3db0 --- /dev/null +++ b/FreeSql/Properties/CoreStrings.en-US.resx @@ -0,0 +1,498 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + [Table(AsTable="{asTable}")] Property value formatted incorrectly + + + The property name {atmGroupsValue} set by [Table (AsTable = xx)] is not of type DateTime + + + {name}: Failed to get resource {statistics} + + + {name}: An exception needs to be thrown + + + Wrong expression format {column} + + + Select is not available until the Chunk function + + + For security reasons, be sure to use ForUpdate after the transaction is open + + + Cannot be null + + + {name} cannot be null + + + Unable to match {property} + + + {property} cannot be resolved to an expression tree + + + The parameter master ConnectionString cannot be empty, check UseConnectionString + + + Commit + + + Connection failed, ready to switch other available servers + + + Custom expression parsing error: type {exp3MethodDeclaringType} needs to define static ThreadLocal<ExpressionCallContext>field, field, field (important three reminders) + + + Custom {Reflection Information} cannot be empty, format: {static method name}{space}{reflection information} + + + Custom {static method name} cannot be empty, format: {static method name}{space}{reflection information} + + + Custom corresponding {{static method name}}:{fiValueCustomArray} The [DynamicFilterCustomAttribute] attribute is not set + + + Custom requires that Fields be space-split and 2-length in the format: {static method name}{space}{reflection information} + + + The data type of the operation ({dataDisplayCsharp}) is inconsistent with AsType ({tableTypeDisplayCsharp}). Please check. + + + DateRange requires that Value be comma-separated and 2-length + + + DateRange requires that the Value [1] format must be: yyyy, yyyy-MM, yyyy-MM-dd, yyyyy-MM-dd HH, yyyy, yyyy-MM-dd HH:mm + + + The record may not exist, or the row level optimistic lock version is out of date, the number of updates {sourceCount}, the number of rows affected {affrows}. + + + The number of SlaveConnectionStrings is not the same as SlaveWeights + + + ColumnAttribute. Name {colattrName} exists repeatedly, please check (note: case insensitive) + + + Property name {pName} exists repeatedly, please check (note: case insensitive) + + + The {function} feature requires that the entity class {tableCsName} must have a primary key + + + {tbTypeFullName} is a parent-child relationship, but combinations of multiple primary keys are not supported in versions below MySql 8.0 + + + {tbTypeFullName} is not a parent-child relationship and cannot be used + + + This particular subquery cannot be resolved + + + Expression error, its top object is not ParameterExpression:{exp} + + + Expression error, it is not a continuous MemberAccess type: {exp} + + + ExpressionTree conversion type error, value ({value}), type ({valueTypeFullName}), target type ({typeFullName}), Error:{exMessage} + + + Failed to parse table field value {sqlWhere} + + + Function {asTable} not implemented by AsTable + + + GBase does not support separators other than commas at this time + + + TableName:{tableName} generated the same table name + + + The parameter'{primary}'passed by GetPrimarys is incorrect and does not belong to the key name of the dictionary data + + + {first} has already been specified and {second} can no longer be specified + + + {tb2DbName}. {mp2MemberName} is ignored. Check the IsIgnore setting to make sure get/set is public + + + Include parameter type error + + + Include parameter type is wrong, use IncludeMany for collection properties + + + Include parameter type is wrong, expression type should be MemberAccess + + + The property {collMemMemberName} of IncludeMany type {tbTypeDisplayCsharp} is not a valid navigation property, hint: IsIgnore = true will not be a navigation property + + + IncludeMany {navigateSelector} parameter is wrong, Select can only use one parameter's method, the correct format:.Select(t =>new TNavigate{{}}) + + + IncludeMany {navigateSelector} parameter error, Select lambda parameter return value must match {collMemElementType} type + + + IncludeMany parameter 1 has wrong type, expression type should be MemberAccess + + + IncludeMany {navigateSelector} parameter type is wrong, correct format: a.collections.Take(1).Where(c => C.A ID == a.id).Select (a => new TNavigate{{}}) + + + ISelect. InsertInto() did not select an attribute: {displayCsharp} + + + ISelect. InsertInto() type error: {displayCsharp} + + + The InsertOrUpdate function performs merge into requiring the entity class {CsName} to have a primary key + + + The generic parameter for InsertOrUpdate<>does not support {typeofT1}. Pass in your entity class + + + FreeSql needs to be installed for Delayed Loading. Extensions. LazyLoading. Dll, downloadable to nuget + + + {trytbTypeName} Compilation error: {exMessage}\r\n\r\n{cscode} + + + Entity type {trytbTypeName} must be declared public + + + ManyToMany navigation properties. AsSelect() is temporarily unavailable for the Sum/Avg/Max/Min/First/ToOne/ToList method + + + [ManyToMany] Navigation property {trytbTypeName}. {pnvName} did not find a corresponding field in {tbmidCsName}, such as: {midTypePropsTrytbName}{findtrytbPkCsName}, {midTypePropsTrytbName}_ {findtrytbPkCsName} + + + [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, entity type {tbrefTypeName} missing primary key identity, [Column (IsPrimary = true)] + + + [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, entity type {tbrefTypeName} must have a corresponding [Navigate (ManyToMany = x)] collection property + + + [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, {tbmidCsName}. {trycolCsName} and {trytbCsName}. {trytbPrimarysCsName} type inconsistent + + + [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, intermediate class {tbmidCsName}.{midTypePropsTrytbName} Error: {exMessage} + + + [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, intermediate class {tbmidCsName}. The {midTypePropsTrytbName} navigation property is not ManyToOne or OneToOne + + + Mapping exception: {name} None of the property names are the same + + + Ado. MasterPool value is null, this operation cannot self-enable transactions, please explicitly pass [transaction object] resolution + + + Missing FreeSql database implementation package: FreeSql. Provider. {Provider}. Dll, downloadable to nuget + + + The FreeSql database implementation package is missing: {dll} can be downloaded to nuget; If there is {dll} and an error still occurs (due to environmental issues that cause the type to be unreflected), manually pass in typeof ({providerType}) in the third parameter of UseConnectionString/UseConnectionFactory + + + Navigation property {trytbTypeName}. The number of {pnvName} attributes [Navigate] Binds ({bindColumnsCount}) is different from the number of external primary keys ({tbrefPrimarysLength}) + + + {tb2DbName}. {mp2MemberName} Navigation Property Collection forgotten. AsSelect()? If used in ToList (a => a. {mp2MemberName}), step by step to refer to the IncludeMany document. + + + [Navigation Properties]{trytbTypeDisplayCsharp}. Missing set attribute for {pName} + + + Navigation property {trytbTypeName}. {pnvName} No corresponding fields were found, such as: {pnvName}{findtbrefPkCsName}, {pnvName}_ {findtbrefPkCsName}. Or use the [Navigate] attribute to specify the relationship mapping. + + + Navigation property {trytbTypeName}. {pnvName} parsing error, entity type {trytcTypeName} missing primary key identity, [Column (IsPrimary = true)] + + + Navigation property {trytbTypeName}. {pnvName} parsing error, {trytbCsName}. {trycolCsName} and {tbrefCsName}. {tbrefPrimarysCsName} type inconsistent + + + Navigation property {trytbTypeName}. {pnvName} attribute [Navigate] parsing error, property not found at {tbrefTypeName}: {bi} + + + {tableTypeDisplayCsharp} has no primary key defined and cannot use SetSource. Try SetDto + + + No properties defined + + + Not implemented + + + Function expression {exp} parsing not implemented + + + Function expression {exp} parsing not implemented, parameter {expArguments} must be constant + + + Function expression {exp} parsing is not implemented. Use if you are working on a navigation property collection. AsSelect (). {exp3MethodName} ({exp3ArgumentsCount}) + + + Constant under MemberAccess is not implemented + + + {name} is not implemented + + + I won't support it + + + {dataType} does not support OrderByRandom sorting + + + {property} is not a valid navigation property + + + {dbName} Column {memberName} not found + + + Cannot find the column corresponding to {CsName} + + + Attribute not found: {memberName} + + + Property name {proto} not found + + + Custom could not find the corresponding {{reflection information}}:{fiValueCustomArray} + + + Custom could not find the corresponding {{static method name}}:{fiValueCustomArray} + + + The property name {atmGroupsValue} set by [Table(AsTable = xx)] does not exist + + + No UseConnectionString or UseConnectionFactory specified + + + [{policyName}] ObjectPool. {GetName}() timeout {totalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081 + + + [{policyName}] ObjectPool. GetAsync() The queue is too long. Policy. AsyncGetCapacity = {asyncGetCapacity} + + + [OneToMany] Navigation property {trytbTypeName}.{pnvName} did not find a corresponding field in {tbrefCsName}, such as: {findtrytb}{findtrytbPkCsName}, {findtrytb}_{findtrytbPkCsName} + + + [OneToMany] Navigation property {trytbTypeName}.{pnvName} parsing error, {trytbCsName}.{trytbPrimarysCsName} and {tbrefCsName}.{trycolCsName} is of inconsistent type + + + , {refpropName}{findtrytbPkCsName}, {refpropName}_{findtrytbPkCsName}. Or use the [Navigate] attribute to specify the relationship mapping. + + + Parameter field not specified + + + The {property} parameter is incorrect, it is not a collection property and must be IList<T>or ICollection<T> + + + The {property} parameter is incorrect, it is not a valid navigation property + + + {where} parameter error, {keyval} is not a valid property name and cannot be found in entity class {reftbTypeDisplayCsharp} + + + {property} parameter error, format "TopicId=Id, multiple groups using comma connection" + + + Parsing failed {callExpMethodName} {message} + + + [{policyName}] The ObjectPool has been disposed, see: https://github.com/dotnetcore/FreeSql/discussions/1079 + + + The {policyName} status is unavailable and cannot be used until the background checker is restored. {UnavailableExceptionMessage} + + + The property {trytbVersionColumnCsName} is labeled as a row lock (optimistic lock) (IsVersion), but it must be a numeric type or byte[], and it cannot be Nullable + + + Properrties parameter cannot be empty + + + {property} property name not found + + + Range requires that Value be comma-separated and 2-length + + + RollBack + + + Runtime error, reflection failed to get IncludeMany method + + + {qoteSql} is NULL unless the attribute [Column (IsNullable = false)] + + + Subtable field value'{dt}'cannot be less than'{beginTime}' + + + Subtable field value cannot be null + + + The tabular field value'{columnValue}'cannot be converted to DateTime + + + Table field value'{dt}'does not match table name + + + Type T2 Error + + + TableName format error, example: "log_{yyyyMMdd}" + + + {Type}. AsType parameter error, please pass in the correct entity type + + + The {thatFullName} type cannot access the constructor + + + {name} type error + + + {Type}. AsType parameter does not support specifying as object + + + Type {typeofFullName} error, IncludeMany cannot be used + + + Unable to parse expression: {exp} + + + Unable to parse expression method {exp3tmpCallMethodName} + + + Please use fsql. InsertDict (dict) method inserts dictionary data + + \ No newline at end of file diff --git a/FreeSql/Properties/CoreStrings.resx b/FreeSql/Properties/CoreStrings.resx new file mode 100644 index 000000000..e3c295105 --- /dev/null +++ b/FreeSql/Properties/CoreStrings.resx @@ -0,0 +1,498 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + [Table(AsTable = "{asTable}")] 特性值格式错误 + + + [Table(AsTable = xx)] 设置的属性名 {atmGroupsValue} 不是 DateTime 类型 + + + {name}: Failed to get resource {statistics} + + + {name}: An exception needs to be thrown + + + 错误的表达式格式 {column} + + + Chunk 功能之前不可使用 Select + + + 安全起见,请务必在事务开启之后,再使用 ForUpdate + + + 不能为 null + + + {name} 不能为 null + + + 无法匹配 {property} + + + {property} 无法解析为表达式树 + + + 参数 masterConnectionString 不可为空,请检查 UseConnectionString + + + 提交 + + + 连接失败,准备切换其他可用服务器 + + + 自定义表达式解析错误:类型 {exp3MethodDeclaringType} 需要定义 static ThreadLocal<ExpressionCallContext> 字段、字段、字段(重要三次提醒) + + + Custom { 反射信息 }不能为空,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } + + + Custom { 静态方法名 }不能为空,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } + + + Custom 对应的{{ 静态方法名 }}:{fiValueCustomArray} 未设置 [DynamicFilterCustomAttribute] 特性 + + + Custom 要求 Field 应该空格分割,并且长度为 2,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } + + + 操作的数据类型({dataDisplayCsharp}) 与 AsType({tableTypeDisplayCsharp}) 不一致,请检查。 + + + DateRange 要求 Value 应该逗号分割,并且长度为 2 + + + DateRange 要求 Value[1] 格式必须为:yyyy、yyyy-MM、yyyy-MM-dd、yyyy-MM-dd HH、yyyy、yyyy-MM-dd HH:mm + + + 记录可能不存在,或者【行级乐观锁】版本过旧,更新数量{sourceCount},影响的行数{affrows}。 + + + SlaveConnectionString 数量与 SlaveWeights 不相同 + + + ColumnAttribute.Name {colattrName} 重复存在,请检查(注意:不区分大小写) + + + 属性名 {pName} 重复存在,请检查(注意:不区分大小写) + + + {function} 功能要求实体类 {tableCsName} 必须有主键 + + + {tbTypeFullName} 是父子关系,但是 MySql 8.0 以下版本中不支持组合多主键 + + + {tbTypeFullName} 不是父子关系,无法使用该功能 + + + 这个特别的子查询不能解析 + + + 表达式错误,它的顶级对象不是 ParameterExpression:{exp} + + + 表达式错误,它不是连续的 MemberAccess 类型:{exp} + + + ExpressionTree 转换类型错误,值({value}),类型({valueTypeFullName}),目标类型({typeFullName}),{exMessage} + + + 未能解析分表字段值 {sqlWhere} + + + AsTable 未实现的功能 {asTable} + + + GBase 暂时不支持逗号以外的分割符 + + + tableName:{tableName} 生成了相同的分表名 + + + GetPrimarys 传递的参数 "{primary}" 不正确,它不属于字典数据的键名 + + + 已经指定了 {first},不能再指定 {second} + + + {tb2DbName}.{mp2MemberName} 被忽略,请检查 IsIgnore 设置,确认 get/set 为 public + + + Include 参数类型错误 + + + Include 参数类型错误,集合属性请使用 IncludeMany + + + Include 参数类型错误,表达式类型应该为 MemberAccess + + + IncludeMany 类型 {tbTypeDisplayCsharp} 的属性 {collMemMemberName} 不是有效的导航属性,提示:IsIgnore = true 不会成为导航属性 + + + IncludeMany {navigateSelector} 参数错误,Select 只可以使用一个参数的方法,正确格式:.Select(t =>new TNavigate {{}}) + + + IncludeMany {navigateSelector} 参数错误,Select lambda参数返回值必须和 {collMemElementType} 类型一致 + + + IncludeMany 参数1 类型错误,表达式类型应该为 MemberAccess + + + IncludeMany {navigateSelector} 参数类型错误,正确格式: a.collections.Take(1).Where(c =>c.aid == a.id).Select(a=> new TNavigate{{}}) + + + ISelect.InsertInto() 未选择属性: {displayCsharp} + + + ISelect.InsertInto() 类型错误: {displayCsharp} + + + InsertOrUpdate 功能执行 merge into 要求实体类 {CsName} 必须有主键 + + + InsertOrUpdate<>的泛型参数 不支持 {typeofT1},请传递您的实体类 + + + 【延时加载】功能需要安装 FreeSql.Extensions.LazyLoading.dll,可前往 nuget 下载 + + + 【延时加载】{trytbTypeName} 编译错误:{exMessage}\r\n\r\n{cscode} + + + 【延时加载】实体类型 {trytbTypeName} 必须声明为 public + + + ManyToMany 导航属性 .AsSelect() 暂时不可用于 Sum/Avg/Max/Min/First/ToOne/ToList 方法 + + + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 在 {tbmidCsName} 中没有找到对应的字段,如:{midTypePropsTrytbName}{findtrytbPkCsName}、{midTypePropsTrytbName}_{findtrytbPkCsName} + + + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {tbrefTypeName} 缺少主键标识,[Column(IsPrimary = true)] + + + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {tbrefTypeName} 必须存在对应的 [Navigate(ManyToMany = x)] 集合属性 + + + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,{tbmidCsName}.{trycolCsName} 和 {trytbCsName}.{trytbPrimarysCsName} 类型不一致 + + + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,中间类 {tbmidCsName}.{midTypePropsTrytbName} 错误:{exMessage} + + + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,中间类 {tbmidCsName}.{midTypePropsTrytbName} 导航属性不是【ManyToOne】或【OneToOne】 + + + 映射异常:{name} 没有一个属性名相同 + + + Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决 + + + 缺少 FreeSql 数据库实现包:FreeSql.Provider.{Provider}.dll,可前往 nuget 下载 + + + 缺少 FreeSql 数据库实现包:{dll},可前往 nuget 下载;如果存在 {dll} 依然报错(原因是环境问题导致反射不到类型),请在 UseConnectionString/UseConnectionFactory 第三个参数手工传入 typeof({providerType}) + + + 导航属性 {trytbTypeName}.{pnvName} 特性 [Navigate] Bind 数目({bindColumnsCount}) 与 外部主键数目({tbrefPrimarysLength}) 不相同 + + + {tb2DbName}.{mp2MemberName} 导航属性集合忘了 .AsSelect() 吗?如果在 ToList(a => a.{mp2MemberName}) 中使用,请移步参考 IncludeMany 文档。 + + + 【导航属性】{trytbTypeDisplayCsharp}.{pName} 缺少 set 属性 + + + 导航属性 {trytbTypeName}.{pnvName} 没有找到对应的字段,如:{pnvName}{findtbrefPkCsName}、{pnvName}_{findtbrefPkCsName}。或者使用 [Navigate] 特性指定关系映射。 + + + 导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {trytcTypeName} 缺少主键标识,[Column(IsPrimary = true)] + + + 导航属性 {trytbTypeName}.{pnvName} 解析错误,{trytbCsName}.{trycolCsName} 和 {tbrefCsName}.{tbrefPrimarysCsName} 类型不一致 + + + 导航属性 {trytbTypeName}.{pnvName} 特性 [Navigate] 解析错误,在 {tbrefTypeName} 未找到属性:{bi} + + + {tableTypeDisplayCsharp} 没有定义主键,无法使用 SetSource,请尝试 SetDto + + + 没有定义属性 + + + 未实现 + + + 未实现函数表达式 {exp} 解析 + + + 未实现函数表达式 {exp} 解析,参数 {expArguments} 必须为常量 + + + 未实现函数表达式 {exp} 解析,如果正在操作导航属性集合,请使用 .AsSelect().{exp3MethodName}({exp3ArgumentsCount}) + + + 未实现 MemberAccess 下的 Constant + + + 未实现 {name} + + + 不支持 + + + {dataType} 不支持 OrderByRandom 随机排序 + + + {property} 不是有效的导航属性 + + + {dbName} 找不到列 {memberName} + + + 找不到 {CsName} 对应的列 + + + 找不到属性:{memberName} + + + 找不到属性名 {proto} + + + Custom 找不到对应的{{ 反射信息 }}:{fiValueCustomArray} + + + Custom 找不到对应的{{ 静态方法名 }}:{fiValueCustomArray} + + + [Table(AsTable = xx)] 设置的属性名 {atmGroupsValue} 不存在 + + + 未指定 UseConnectionString 或者 UseConnectionFactory + + + 【{policyName}】ObjectPool.{GetName}() timeout {totalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081 + + + 【{policyName}】ObjectPool.GetAsync() The queue is too long. Policy.AsyncGetCapacity = {asyncGetCapacity} + + + 【OneToMany】导航属性 {trytbTypeName}.{pnvName} 在 {tbrefCsName} 中没有找到对应的字段,如:{findtrytb}{findtrytbPkCsName}、{findtrytb}_{findtrytbPkCsName} + + + 【OneToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,{trytbCsName}.{trytbPrimarysCsName} 和 {tbrefCsName}.{trycolCsName} 类型不一致 + + + 、{refpropName}{findtrytbPkCsName}、{refpropName}_{findtrytbPkCsName}。或者使用 [Navigate] 特性指定关系映射。 + + + 参数 field 未指定 + + + {property} 参数错误,它不是集合属性,必须为 IList<T> 或者 ICollection<T> + + + {property} 参数错误,它不是有效的导航属性 + + + {where} 参数错误,{keyval} 不是有效的属性名,在实体类 {reftbTypeDisplayCsharp} 无法找到 + + + {property} 参数错误,格式 "TopicId=Id,多组使用逗号连接" + + + 解析失败 {callExpMethodName} {message} + + + 【{policyName}】The ObjectPool has been disposed, see: https://github.com/dotnetcore/FreeSql/discussions/1079 + + + 【{policyName}】状态不可用,等待后台检查程序恢复方可使用。{UnavailableExceptionMessage} + + + 属性{trytbVersionColumnCsName} 被标注为行锁(乐观锁)(IsVersion),但其必须为数字类型 或者 byte[],并且不可为 Nullable + + + properties 参数不能为空 + + + {property} 属性名无法找到 + + + Range 要求 Value 应该逗号分割,并且长度为 2 + + + 回滚 + + + 运行时错误,反射获取 IncludeMany 方法失败 + + + {qoteSql} is NULL,除非设置特性 [Column(IsNullable = false)] + + + 分表字段值 "{dt}" 不能小于 "{beginTime} " + + + 分表字段值不能为 null + + + 分表字段值 "{columnValue}" 不能转化成 DateTime + + + 分表字段值 "{dt}" 未匹配到分表名 + + + T2 类型错误 + + + tableName 格式错误,示例:“log_{yyyyMMdd}” + + + {Type}.AsType 参数错误,请传入正确的实体类型 + + + {thatFullName} 类型无法访问构造函数 + + + {name} 类型错误 + + + {Type}.AsType 参数不支持指定为 object + + + 类型 {typeofFullName} 错误,不能使用 IncludeMany + + + 无法解析表达式:{exp} + + + 无法解析表达式方法 {exp3tmpCallMethodName} + + + 请使用 fsql.InsertDict(dict) 方法插入字典数据 + + \ No newline at end of file diff --git a/FreeSql/Properties/Resources.tt b/FreeSql/Properties/Resources.tt new file mode 100644 index 000000000..104552ee5 --- /dev/null +++ b/FreeSql/Properties/Resources.tt @@ -0,0 +1,261 @@ +<#@ template hostspecific="true" #> +<#@ assembly name="System.Core" #> +<#@ assembly name="EnvDTE" #> +<#@ assembly name="System.Windows.Forms" #> +<#@ import namespace="System.Collections" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.ComponentModel.Design" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Resources" #> +<#@ import namespace="System.Text.RegularExpressions" #> +<#@ import namespace="EnvDTE" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #> + +<# + var model = LoadResources(); +#> +// + +using System; +using System.Reflection; +using System.Resources; +<# + if (!model.NoDiagnostics) + { +#> +using System.Threading; +<# + } +#> + +namespace <#= model.Namespace #> +{ +<# + if (model.Namespace.EndsWith("Internal") + || model.AccessModifier == "internal") + { +#> + /// + /// This is an internal API that supports the FreeSql infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new FreeSql release. + /// +<# + } + else + { +#> + /// + /// + /// String resources used in FreeSql exceptions, etc. + /// + /// + /// These strings are exposed publicly for use by database providers and extensions. + /// It is unusual for application code to need these strings. + /// + /// +<# + } +#> + <#= model.AccessModifier #> static class <#= model.Class #> + { + private static readonly ResourceManager _resourceManager + = new ResourceManager("<#= model.ResourceName #>", typeof(<#= model.Class #>).Assembly); +<# + foreach (var resource in model.Resources) + { +#> + + /// +<# + foreach (var line in Lines(resource.Value)) + { +#> + /// <#= Xml(line) #> +<# + } +#> + /// +<# + if (resource.Obsolete) + { +#> + [Obsolete] +<# + } + + if (resource.Parameters.Any()) + { +#> + public static string <#= resource.Name #>(<#= List("object ", resource.Parameters.Select(e => e.ParamString)) #>) + => string.Format( + GetString("<#= resource.Name #>", <#= List(resource.Parameters.Select(e => e.NameOfString)) #>), + <#= List(resource.Parameters.Select(e => e.ParamString)) #>); +<# + } + else + { +#> + public static string <#= resource.Name #> + => GetString("<#= resource.Name #>"); +<# + } + } +#> + + private static string GetString(string name, params string[] formatterNames) + { + var value = _resourceManager.GetString(name); + for (var i = 0; i < formatterNames.Length; i++) + { + value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}"); + } + + return value; + } + } +} + +<#+ + ResourceFile LoadResources() + { + var result = new ResourceFile(); + + if (Session.ContainsKey("AccessModifier")) + { + result.AccessModifier = (string)Session["AccessModifier"]; + }; + + var services = (IServiceProvider)Host; + var dte = (DTE)services.GetCOMService(typeof(DTE)); + if (!Session.TryGetValue("NoDiagnostics", out var noDiagnostics)) + { + noDiagnostics = false; + } + + result.NoDiagnostics = (bool)noDiagnostics; + + var resourceFile = (string)Session["ResourceFile"]; + if (!Path.IsPathRooted(resourceFile)) + { + resourceFile = Host.ResolvePath(resourceFile); + } + + var resourceProjectItem = dte.Solution.FindProjectItem(resourceFile); + var templateProjectItem = dte.Solution.FindProjectItem(Host.TemplateFile); + var project = templateProjectItem.ContainingProject; + var rootNamespace = (string)project.Properties.Item("RootNamespace").Value; + var resourceDir = Path.GetDirectoryName(resourceFile); + var projectDir = (string)project.Properties.Item("FullPath").Value; + var resourceNamespace = rootNamespace + "." + resourceDir.Substring(projectDir.Length) + .Replace(Path.DirectorySeparatorChar, '.'); + + result.Namespace = (string)resourceProjectItem.Properties.Item("CustomToolNamespace")?.Value; + if (string.IsNullOrEmpty(result.Namespace)) + { + result.Namespace = resourceNamespace; + } + + result.Class = Path.GetFileNameWithoutExtension(resourceFile); + + + result.ResourceName = resourceNamespace + "." + result.Class; + + List sortedResources; + using (var reader = new ResXResourceReader(resourceFile)) + { + reader.UseResXDataNodes = true; + sortedResources = Enumerable.ToList( + from DictionaryEntry r in reader + orderby r.Key + select (ResXDataNode)r.Value); + + result.Resources = sortedResources + .Select(r => new Resource(r)) + .ToList(); + } + + using (var writer = new ResXResourceWriter(resourceFile)) + { + foreach (var node in sortedResources) + writer.AddResource(node); + + writer.Generate(); + } + + return result; + } + + IEnumerable Lines(string value) + => value.Split(new[] { Environment.NewLine }, StringSplitOptions.None); + + string Xml(string value) + => value.Replace("<", "<").Replace(">", ">"); + + string List(IEnumerable items) + => List(null, items); + + string List(string prefix, IEnumerable items, string suffix = null) + => string.Join(", ", items.Select(i => prefix + i + suffix)); + + class ResourceFile + { + public string Namespace { get; set; } + public string AccessModifier { get; set; } = "public"; + public string Class { get; set; } + public string ResourceName { get; set; } + public IEnumerable Resources { get; set; } + public bool NoDiagnostics { get; set; } + } + + class Resource + { + public Resource(ResXDataNode node) + { + Name = node.Name; + Value = (string)node.GetValue((ITypeResolutionService)null); + var parameters = Regex.Matches(Value, @"\{(\w+)\}") + .Cast() + .Select(m => m.Groups[1].Value) + .Distinct() + .Select(n => ("nameof(" + n + ")", n)) + .ToList(); + + foreach (var parameter in parameters.ToList()) + { + var rawString = parameter.Item2; + var underscoreIndex = rawString.IndexOf('_'); + if (underscoreIndex > 0) + { + var newIndex = int.Parse(rawString.Substring(0, underscoreIndex)); + parameters[newIndex] = ("\"" + rawString + "\"", rawString.Substring(underscoreIndex + 1)); + } + } + + Parameters = parameters; + + var eventInfo = node.Comment.Split(' '); + var argumentsRead = 0; + if (eventInfo.FirstOrDefault() == "Obsolete") + { + Obsolete = true; + argumentsRead++; + } + + Level = eventInfo.Skip(argumentsRead++).FirstOrDefault() ?? "BadLevel"; + EventId = eventInfo.Skip(argumentsRead++).FirstOrDefault() ?? "BadEventId"; + Types = eventInfo.Skip(argumentsRead++).ToList(); + } + + public string Name { get; } + public string Value { get; } + public string EventId { get; } + public string Level { get; } + public bool Obsolete { get; } + public IEnumerable<(string NameOfString, string ParamString)> Parameters { get; } + public IEnumerable Types { get; } + } +#> \ No newline at end of file diff --git a/Providers/FreeSql.Provider.ClickHouse/ClickHouseExpression.cs b/Providers/FreeSql.Provider.ClickHouse/ClickHouseExpression.cs index 77a6dfeae..b030df44f 100644 --- a/Providers/FreeSql.Provider.ClickHouse/ClickHouseExpression.cs +++ b/Providers/FreeSql.Provider.ClickHouse/ClickHouseExpression.cs @@ -281,7 +281,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); if (exp.Arguments.Count == 1) return ExpressionLambdaToSql(exp.Arguments[0], tsc); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); diff --git a/Providers/FreeSql.Provider.Dameng/Curd/DamengInsertOrUpdate.cs b/Providers/FreeSql.Provider.Dameng/Curd/DamengInsertOrUpdate.cs index 345da6bce..48cadbbcb 100644 --- a/Providers/FreeSql.Provider.Dameng/Curd/DamengInsertOrUpdate.cs +++ b/Providers/FreeSql.Provider.Dameng/Curd/DamengInsertOrUpdate.cs @@ -31,7 +31,7 @@ public override string ToSql() string getMergeSql(List data) { - if (_table.Primarys.Any() == false) throw new Exception($"InsertOrUpdate 功能执行 merge into 要求实体类 {_table.CsName} 必须有主键"); + if (_table.Primarys.Any() == false) throw new Exception(CoreStrings.InsertOrUpdate_Must_Primary_Key(_table.CsName)); var sb = new StringBuilder().Append("MERGE INTO ").Append(_commonUtils.QuoteSqlName(TableRuleInvoke())).Append(" t1 \r\nUSING ("); WriteSourceSelectUnionAll(data, sb, dbParams); diff --git a/Providers/FreeSql.Provider.Dameng/DamengExpression.cs b/Providers/FreeSql.Provider.Dameng/DamengExpression.cs index 87d0a74b6..cea449c3f 100644 --- a/Providers/FreeSql.Provider.Dameng/DamengExpression.cs +++ b/Providers/FreeSql.Provider.Dameng/DamengExpression.cs @@ -266,7 +266,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); //3个 {} 时,Arguments 解析出来是分开的 diff --git a/Providers/FreeSql.Provider.Firebird/Curd/FirebirdInsertOrUpdate.cs b/Providers/FreeSql.Provider.Firebird/Curd/FirebirdInsertOrUpdate.cs index 82d362731..83ef52300 100644 --- a/Providers/FreeSql.Provider.Firebird/Curd/FirebirdInsertOrUpdate.cs +++ b/Providers/FreeSql.Provider.Firebird/Curd/FirebirdInsertOrUpdate.cs @@ -31,7 +31,7 @@ public override string ToSql() string getMergeSql(List data) { - if (_table.Primarys.Any() == false) throw new Exception($"InsertOrUpdate 功能执行 merge into 要求实体类 {_table.CsName} 必须有主键"); + if (_table.Primarys.Any() == false) throw new Exception(CoreStrings.InsertOrUpdate_Must_Primary_Key(_table.CsName)); var sb = new StringBuilder().Append("MERGE INTO ").Append(_commonUtils.QuoteSqlName(TableRuleInvoke())).Append(" t1 \r\nUSING ("); WriteSourceSelectUnionAll(data, sb, dbParams); diff --git a/Providers/FreeSql.Provider.Firebird/FirebirdExpression.cs b/Providers/FreeSql.Provider.Firebird/FirebirdExpression.cs index f5c55353c..f19f2815c 100644 --- a/Providers/FreeSql.Provider.Firebird/FirebirdExpression.cs +++ b/Providers/FreeSql.Provider.Firebird/FirebirdExpression.cs @@ -253,7 +253,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); //3个 {} 时,Arguments 解析出来是分开的 diff --git a/Providers/FreeSql.Provider.GBase/Curd/GBaseInsertOrUpdate.cs b/Providers/FreeSql.Provider.GBase/Curd/GBaseInsertOrUpdate.cs index afc8a6746..7b03afdfd 100644 --- a/Providers/FreeSql.Provider.GBase/Curd/GBaseInsertOrUpdate.cs +++ b/Providers/FreeSql.Provider.GBase/Curd/GBaseInsertOrUpdate.cs @@ -31,7 +31,7 @@ public override string ToSql() string getMergeSql(List data) { - if (_table.Primarys.Any() == false) throw new Exception($"InsertOrUpdate 功能执行 merge into 要求实体类 {_table.CsName} 必须有主键"); + if (_table.Primarys.Any() == false) throw new Exception(CoreStrings.InsertOrUpdate_Must_Primary_Key(_table.CsName)); var sb = new StringBuilder().Append("MERGE INTO ").Append(_commonUtils.QuoteSqlName(TableRuleInvoke())).Append(" t1 \r\nUSING ("); WriteSourceSelectUnionAll(data, sb, dbParams); diff --git a/Providers/FreeSql.Provider.GBase/GBaseExpression.cs b/Providers/FreeSql.Provider.GBase/GBaseExpression.cs index 09ab33048..bcee848a8 100644 --- a/Providers/FreeSql.Provider.GBase/GBaseExpression.cs +++ b/Providers/FreeSql.Provider.GBase/GBaseExpression.cs @@ -253,7 +253,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); //3个 {} 时,Arguments 解析出来是分开的 diff --git a/Providers/FreeSql.Provider.KingbaseES/KingbaseESExpression.cs b/Providers/FreeSql.Provider.KingbaseES/KingbaseESExpression.cs index a35cc007e..2407ed649 100644 --- a/Providers/FreeSql.Provider.KingbaseES/KingbaseESExpression.cs +++ b/Providers/FreeSql.Provider.KingbaseES/KingbaseESExpression.cs @@ -328,7 +328,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); //3个 {} 时,Arguments 解析出来是分开的 diff --git a/Providers/FreeSql.Provider.MsAccess/MsAccessExpression.cs b/Providers/FreeSql.Provider.MsAccess/MsAccessExpression.cs index f84d795f7..ff8fba6bb 100644 --- a/Providers/FreeSql.Provider.MsAccess/MsAccessExpression.cs +++ b/Providers/FreeSql.Provider.MsAccess/MsAccessExpression.cs @@ -236,7 +236,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), exp.Arguments.Select(a => a.Type).ToArray()); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); //3个 {} 时,Arguments 解析出来是分开的 diff --git a/Providers/FreeSql.Provider.MySql/MySqlExpression.cs b/Providers/FreeSql.Provider.MySql/MySqlExpression.cs index 57aee99b3..837682d4d 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlExpression.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlExpression.cs @@ -264,7 +264,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); if (exp.Arguments.Count == 1) return ExpressionLambdaToSql(exp.Arguments[0], tsc); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); diff --git a/Providers/FreeSql.Provider.Odbc/Dameng/Curd/OdbcDamengInsertOrUpdate.cs b/Providers/FreeSql.Provider.Odbc/Dameng/Curd/OdbcDamengInsertOrUpdate.cs index a6422179c..7863330c9 100644 --- a/Providers/FreeSql.Provider.Odbc/Dameng/Curd/OdbcDamengInsertOrUpdate.cs +++ b/Providers/FreeSql.Provider.Odbc/Dameng/Curd/OdbcDamengInsertOrUpdate.cs @@ -31,7 +31,7 @@ public override string ToSql() string getMergeSql(List data) { - if (_table.Primarys.Any() == false) throw new Exception($"InsertOrUpdate 功能执行 merge into 要求实体类 {_table.CsName} 必须有主键"); + if (_table.Primarys.Any() == false) throw new Exception(CoreStrings.InsertOrUpdate_Must_Primary_Key(_table.CsName)); var sb = new StringBuilder().Append("MERGE INTO ").Append(_commonUtils.QuoteSqlName(TableRuleInvoke())).Append(" t1 \r\nUSING ("); WriteSourceSelectUnionAll(data, sb, dbParams); diff --git a/Providers/FreeSql.Provider.Odbc/Dameng/OdbcDamengExpression.cs b/Providers/FreeSql.Provider.Odbc/Dameng/OdbcDamengExpression.cs index dcefdd6ba..0cd91f0f0 100644 --- a/Providers/FreeSql.Provider.Odbc/Dameng/OdbcDamengExpression.cs +++ b/Providers/FreeSql.Provider.Odbc/Dameng/OdbcDamengExpression.cs @@ -266,7 +266,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); //3个 {} 时,Arguments 解析出来是分开的 diff --git a/Providers/FreeSql.Provider.Odbc/KingbaseES/OdbcKingbaseESExpression.cs b/Providers/FreeSql.Provider.Odbc/KingbaseES/OdbcKingbaseESExpression.cs index cb33402cc..1b881d300 100644 --- a/Providers/FreeSql.Provider.Odbc/KingbaseES/OdbcKingbaseESExpression.cs +++ b/Providers/FreeSql.Provider.Odbc/KingbaseES/OdbcKingbaseESExpression.cs @@ -328,7 +328,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); //3个 {} 时,Arguments 解析出来是分开的 diff --git a/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlExpression.cs b/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlExpression.cs index a0734a6d6..1536aa337 100644 --- a/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlExpression.cs +++ b/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlExpression.cs @@ -262,7 +262,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); if (exp.Arguments.Count == 1) return ExpressionLambdaToSql(exp.Arguments[0], tsc); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); diff --git a/Providers/FreeSql.Provider.Odbc/Oracle/Curd/OdbcOracleInsertOrUpdate.cs b/Providers/FreeSql.Provider.Odbc/Oracle/Curd/OdbcOracleInsertOrUpdate.cs index 706663505..f60feef52 100644 --- a/Providers/FreeSql.Provider.Odbc/Oracle/Curd/OdbcOracleInsertOrUpdate.cs +++ b/Providers/FreeSql.Provider.Odbc/Oracle/Curd/OdbcOracleInsertOrUpdate.cs @@ -31,7 +31,7 @@ public override string ToSql() string getMergeSql(List data) { - if (_table.Primarys.Any() == false) throw new Exception($"InsertOrUpdate 功能执行 merge into 要求实体类 {_table.CsName} 必须有主键"); + if (_table.Primarys.Any() == false) throw new Exception(CoreStrings.InsertOrUpdate_Must_Primary_Key(_table.CsName)); var sb = new StringBuilder().Append("MERGE INTO ").Append(_commonUtils.QuoteSqlName(TableRuleInvoke())).Append(" t1 \r\nUSING ("); WriteSourceSelectUnionAll(data, sb, dbParams); diff --git a/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleExpression.cs b/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleExpression.cs index 9db90126c..3a00f03c4 100644 --- a/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleExpression.cs +++ b/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleExpression.cs @@ -266,7 +266,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); //3个 {} 时,Arguments 解析出来是分开的 diff --git a/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLExpression.cs b/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLExpression.cs index d9dedb29b..5b63b740a 100644 --- a/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLExpression.cs +++ b/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLExpression.cs @@ -350,7 +350,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); //3个 {} 时,Arguments 解析出来是分开的 diff --git a/Providers/FreeSql.Provider.Odbc/SqlServer/Curd/OdbcSqlServerInsertOrUpdate.cs b/Providers/FreeSql.Provider.Odbc/SqlServer/Curd/OdbcSqlServerInsertOrUpdate.cs index 8f090733b..df3af8a1b 100644 --- a/Providers/FreeSql.Provider.Odbc/SqlServer/Curd/OdbcSqlServerInsertOrUpdate.cs +++ b/Providers/FreeSql.Provider.Odbc/SqlServer/Curd/OdbcSqlServerInsertOrUpdate.cs @@ -31,7 +31,7 @@ public override string ToSql() string getMergeSql(List data) { - if (_table.Primarys.Any() == false) throw new Exception($"InsertOrUpdate 功能执行 merge into 要求实体类 {_table.CsName} 必须有主键"); + if (_table.Primarys.Any() == false) throw new Exception(CoreStrings.InsertOrUpdate_Must_Primary_Key(_table.CsName)); var sb = new StringBuilder(); if (IdentityColumn != null) sb.Append("SET IDENTITY_INSERT ").Append(_commonUtils.QuoteSqlName(TableRuleInvoke())).Append(" ON;\r\n"); diff --git a/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerExpression.cs b/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerExpression.cs index ebafc3735..b2c416973 100644 --- a/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerExpression.cs +++ b/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerExpression.cs @@ -272,7 +272,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), exp.Arguments.Select(a => a.Type).ToArray()); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgs0 = ExpressionLambdaToSql(exp.Arguments[0], tsc); if (exp.Arguments.Count == 1) return expArgs0; var nchar = expArgs0.StartsWith("N'") ? "N" : ""; diff --git a/Providers/FreeSql.Provider.Oracle/Curd/OracleInsertOrUpdate.cs b/Providers/FreeSql.Provider.Oracle/Curd/OracleInsertOrUpdate.cs index f1b09eaa0..43b291999 100644 --- a/Providers/FreeSql.Provider.Oracle/Curd/OracleInsertOrUpdate.cs +++ b/Providers/FreeSql.Provider.Oracle/Curd/OracleInsertOrUpdate.cs @@ -31,7 +31,7 @@ public override string ToSql() string getMergeSql(List data) { - if (_table.Primarys.Any() == false) throw new Exception($"InsertOrUpdate 功能执行 merge into 要求实体类 {_table.CsName} 必须有主键"); + if (_table.Primarys.Any() == false) throw new Exception(CoreStrings.InsertOrUpdate_Must_Primary_Key(_table.CsName)); var sb = new StringBuilder().Append("MERGE INTO ").Append(_commonUtils.QuoteSqlName(TableRuleInvoke())).Append(" t1 \r\nUSING ("); WriteSourceSelectUnionAll(data, sb, dbParams); diff --git a/Providers/FreeSql.Provider.Oracle/OracleExpression.cs b/Providers/FreeSql.Provider.Oracle/OracleExpression.cs index 751eb5f4c..e6c337859 100644 --- a/Providers/FreeSql.Provider.Oracle/OracleExpression.cs +++ b/Providers/FreeSql.Provider.Oracle/OracleExpression.cs @@ -266,7 +266,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); //3个 {} 时,Arguments 解析出来是分开的 diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExpression.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExpression.cs index dedd5ef36..524b550a9 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExpression.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExpression.cs @@ -381,7 +381,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); //3个 {} 时,Arguments 解析出来是分开的 diff --git a/Providers/FreeSql.Provider.ShenTong/Curd/ShenTongInsertOrUpdate.cs b/Providers/FreeSql.Provider.ShenTong/Curd/ShenTongInsertOrUpdate.cs index c4ddcd7f5..53ab6a471 100644 --- a/Providers/FreeSql.Provider.ShenTong/Curd/ShenTongInsertOrUpdate.cs +++ b/Providers/FreeSql.Provider.ShenTong/Curd/ShenTongInsertOrUpdate.cs @@ -31,7 +31,7 @@ public override string ToSql() string getMergeSql(List data) { - if (_table.Primarys.Any() == false) throw new Exception($"InsertOrUpdate 功能执行 merge into 要求实体类 {_table.CsName} 必须有主键"); + if (_table.Primarys.Any() == false) throw new Exception(CoreStrings.InsertOrUpdate_Must_Primary_Key(_table.CsName)); var sb = new StringBuilder().Append("MERGE INTO ").Append(_commonUtils.QuoteSqlName(TableRuleInvoke())).Append(" t1 \r\nUSING ("); WriteSourceSelectUnionAll(data, sb, dbParams); diff --git a/Providers/FreeSql.Provider.ShenTong/ShenTongExpression.cs b/Providers/FreeSql.Provider.ShenTong/ShenTongExpression.cs index 70d9c3345..581a78da0 100644 --- a/Providers/FreeSql.Provider.ShenTong/ShenTongExpression.cs +++ b/Providers/FreeSql.Provider.ShenTong/ShenTongExpression.cs @@ -310,7 +310,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); //3个 {} 时,Arguments 解析出来是分开的 diff --git a/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerInsertOrUpdate.cs b/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerInsertOrUpdate.cs index b999844c3..3fc99fd1b 100644 --- a/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerInsertOrUpdate.cs +++ b/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerInsertOrUpdate.cs @@ -31,7 +31,7 @@ public override string ToSql() string getMergeSql(List data) { - if (_table.Primarys.Any() == false) throw new Exception($"InsertOrUpdate 功能执行 merge into 要求实体类 {_table.CsName} 必须有主键"); + if (_table.Primarys.Any() == false) throw new Exception(CoreStrings.InsertOrUpdate_Must_Primary_Key(_table.CsName)); var sb = new StringBuilder(); if (IdentityColumn != null) sb.Append("SET IDENTITY_INSERT ").Append(_commonUtils.QuoteSqlName(TableRuleInvoke())).Append(" ON;\r\n"); diff --git a/Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs b/Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs index a0b80ab89..50d58186c 100644 --- a/Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs +++ b/Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs @@ -271,7 +271,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), exp.Arguments.Select(a => a.Type).ToArray()); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgs0 = ExpressionLambdaToSql(exp.Arguments[0], tsc); if (exp.Arguments.Count == 1) return expArgs0; var nchar = expArgs0.StartsWith("N'") ? "N" : ""; diff --git a/Providers/FreeSql.Provider.Sqlite/SqliteExpression.cs b/Providers/FreeSql.Provider.Sqlite/SqliteExpression.cs index 879b6bc3c..53f561f37 100644 --- a/Providers/FreeSql.Provider.Sqlite/SqliteExpression.cs +++ b/Providers/FreeSql.Provider.Sqlite/SqliteExpression.cs @@ -262,7 +262,7 @@ public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, case "Concat": return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); case "Format": - if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception($"未实现函数表达式 {exp} 解析,参数 {exp.Arguments[0]} 必须为常量"); + if (exp.Arguments[0].NodeType != ExpressionType.Constant) throw new Exception(CoreStrings.Not_Implemented_Expression_ParameterUseConstant(exp,exp.Arguments[0])); var expArgsHack = exp.Arguments.Count == 2 && exp.Arguments[1].NodeType == ExpressionType.NewArrayInit ? (exp.Arguments[1] as NewArrayExpression).Expressions : exp.Arguments.Where((a, z) => z > 0); //3个 {} 时,Arguments 解析出来是分开的 From ba2582b8d142140e51156a17ea52a511488acac8 Mon Sep 17 00:00:00 2001 From: igeekfan Date: Fri, 20 May 2022 03:11:58 +0800 Subject: [PATCH 2/3] Update NoPrimaryKey_UseSetDto --- FreeSql/Properties/CoreStrings.en-US.resx | 2 +- FreeSql/Properties/CoreStrings.resx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/FreeSql/Properties/CoreStrings.en-US.resx b/FreeSql/Properties/CoreStrings.en-US.resx index 9d3cd3db0..29eae3a71 100644 --- a/FreeSql/Properties/CoreStrings.en-US.resx +++ b/FreeSql/Properties/CoreStrings.en-US.resx @@ -337,7 +337,7 @@ Navigation property {trytbTypeName}. {pnvName} attribute [Navigate] parsing error, property not found at {tbrefTypeName}: {bi} - {tableTypeDisplayCsharp} has no primary key defined and cannot use SetSource. Try SetDto + {tableTypeDisplayCsharp} has no primary key defined and cannot use SetSource. Try SetDto or SetSource to specify a temporary primary key No properties defined diff --git a/FreeSql/Properties/CoreStrings.resx b/FreeSql/Properties/CoreStrings.resx index e3c295105..d7036cb33 100644 --- a/FreeSql/Properties/CoreStrings.resx +++ b/FreeSql/Properties/CoreStrings.resx @@ -337,7 +337,7 @@ 导航属性 {trytbTypeName}.{pnvName} 特性 [Navigate] 解析错误,在 {tbrefTypeName} 未找到属性:{bi} - {tableTypeDisplayCsharp} 没有定义主键,无法使用 SetSource,请尝试 SetDto + {tableTypeDisplayCsharp} 没有定义主键,无法使用 SetSource,请尝试 SetDto 或者 SetSource 指定临时主键 没有定义属性 From cdc9b1c5070c2c9249443b2c01e5a23f92c30603 Mon Sep 17 00:00:00 2001 From: igeekfan Date: Sat, 21 May 2022 03:07:25 +0800 Subject: [PATCH 3/3] =?UTF-8?q?#1108=20=20=E6=8A=8A=E8=8B=B1=E6=96=87?= =?UTF-8?q?=E7=9A=84=E4=BD=9C=E4=B8=BA=E9=BB=98=E8=AE=A4=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=EF=BC=8C=E6=8A=8A=E4=B8=AD=E6=96=87=E6=8D=A2=E6=88=90XXX.zh-Ha?= =?UTF-8?q?ns.resx?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FreeSql.DbContext/FreeSql.DbContext.csproj | 4 +- FreeSql.DbContext/FreeSql.DbContext.xml | 99 ++++--- .../Properties/DbContextStrings.Designer.cs | 24 +- ...-US.resx => DbContextStrings.zh-Hans.resx} | 84 +++--- .../Properties/CoreStringsTests.cs | 190 ++++++------- .../Properties/DbContextStringsTests.cs | 10 +- FreeSql/FreeSql.xml | 254 +++++++++--------- FreeSql/Properties/CoreStrings.Designer.cs | 26 +- ...gs.en-US.resx => CoreStrings.zh-Hans.resx} | 248 ++++++++--------- FreeSql/Properties/Resources.tt | 29 +- 10 files changed, 528 insertions(+), 440 deletions(-) rename FreeSql.DbContext/Properties/{DbContextStrings.en-US.resx => DbContextStrings.zh-Hans.resx} (70%) rename FreeSql/Properties/{CoreStrings.en-US.resx => CoreStrings.zh-Hans.resx} (54%) diff --git a/FreeSql.DbContext/FreeSql.DbContext.csproj b/FreeSql.DbContext/FreeSql.DbContext.csproj index c6e643118..3c5d56e66 100644 --- a/FreeSql.DbContext/FreeSql.DbContext.csproj +++ b/FreeSql.DbContext/FreeSql.DbContext.csproj @@ -71,11 +71,11 @@ TextTemplatingFileGenerator DbContextStrings.Designer.cs - + Designer FreeSql - + FreeSql diff --git a/FreeSql.DbContext/FreeSql.DbContext.xml b/FreeSql.DbContext/FreeSql.DbContext.xml index 16c38b489..7c926e6bd 100644 --- a/FreeSql.DbContext/FreeSql.DbContext.xml +++ b/FreeSql.DbContext/FreeSql.DbContext.xml @@ -266,214 +266,220 @@ + + + 重写当前线程的 CurrentUICulture 属性,对 + 使用此强类型资源类的所有资源查找执行重写。 + + - AddFreeDbContext 发生错误,请检查 {dbContextTypeName} 的构造参数都已正确注入 + An error occurred in AddFreeDbContext, check that the construction parameters of {dbContextTypeName} have been injected correctly - 不可添加,已存在于状态管理:{entityString} + Not addable, already exists in state management: {entityString} - 不可添加,实体没有主键:{entityString} + Not addable, entity has no primary key: {entityString} - 不可添加,未设置主键的值:{entityString} + Not addable, no value for primary key set: {entityString} - 不可添加,自增属性有值:{entityString} + Not addable, self-increasing attribute has value: {entityString} - 不可附加,实体没有主键:{entityString} + Not attachable, entity has no primary key: {entityString} - 不可附加,未设置主键的值:{entityString} + Not attachable, no value for primary key set: {entityString} - 不可删除,数据未被跟踪,应该先查询:{entityString} + Not deletable, data not tracked, should query first: {entityString} - 不可删除,实体没有主键:{entityString} + Not deletable, entity has no primary key: {entityString} - 不可删除,未设置主键的值:{entityString} + Not deletable, no value for primary key set: {entityString} - 不可进行编辑,实体没有主键:{entityString} + Not editable, entity has no primary key: {entityString} - 不可更新,数据未被跟踪,应该先查询 或者 Attach:{entityString} + Not updatable, data not tracked, should be queried first or Attach:{entityString} - 不可更新,实体没有主键:{entityString} + Not updatable, entity has no primary key: {entityString} - 不可更新,未设置主键的值:{entityString} + Not updatable, no value for primary key set: {entityString} - 不可更新,数据库不存在该记录:{entityString} + Not updatable, the record does not exist in the database: {entityString} - 请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql + Please configure UseFreeSql in OnConfiguring or AddFreeDbContext - DbSet.AsType 参数错误,请传入正确的实体类型 + DbSet. AsType parameter error, please pass in the correct entity type - 实体类型 {EntityTypeName} 无法转换为 {name},无法使用该方法 + Entity type {EntityTypeName} cannot be converted to {name} and cannot use this method - 实体类型 {EntityTypeName} 主键类型不为 {fullName},无法使用该方法 + Entity type {EntityTypeName} Primary key type is not {fullName} and cannot be used with this method - 实体类型 {EntityTypeName} 主键数量不为 1,无法使用该方法 + Entity type {EntityTypeName} Primary key number is not 1 and cannot be used with this method - FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository + FreeSql. Repository failed to set filter because object does not belong to IRepository - 不可比较,实体没有主键:{entityString} + Not comparable, entity has no primary key: {entityString} - 不可比较,未设置主键的值:{entityString} + Non-comparable, no value for primary key set: {entityString} - FreeSql.Repository Insert 失败,因为设置了过滤器 {filterKey}: {filterValueExpression},插入的数据不符合 {entityString} + FreeSql. Repository Insert failed because the filter {filterKey}: {filterValueExpression} was set and the inserted data does not conform to {entityString} - ISelect.AsType 参数不支持指定为 object + ISelect. AsType parameter does not support specifying as object - {tableTypeFullName} 不存在属性 {propertyName} + Property {propertyName} does not exist for {tableTypeFullName} - 找不到方法 DbSet<>.StatesRemoveByObjects + Method DbSet<> not found. StatesRemoveByObjects - 参数 data 类型错误 {entityTypeFullName} + Parameter data type error {entityTypeFullName} - 参数错误 {param} + Parameter error {param} - 参数错误 {param} 不能为 null + Parameter error {param} cannot be null - 参数错误 {many} 不是集合属性 + Parameter error {many} is not a collection property - 参数错误 {many} 集合属性不存在 + Parameter error {many} Collection property does not exist - 参数错误 {one} 属性不存在 + Parameter error {one} attribute does not exist - Propagation_Mandatory: 使用当前事务,如果没有当前事务,就抛出异常 + Propagation_ Mandatory: With the current transaction, throw an exception if there is no current transaction - Propagation_Never: 以非事务方式执行操作,如果当前事务存在则抛出异常 + Propagation_ Never: Perform the operation non-transactionally and throw an exception if the current transaction exists - {tableTypeFullName} 类型的属性 {propertyName} 不是 OneToMany 或 ManyToMany 特性 + Property {propertyName} of type {tableTypeFullName} is not OneToMany or ManyToMany attribute - 特别错误:批量添加失败,{dataType} 的返回数据,与添加的数目不匹配 + Special error: Bulk add failed, {dataType} returned data, does not match the number added - 特别错误:更新失败,数据未被跟踪:{entityString} + Special error: Update failed, data not tracked: {entityString} - 已开启事务,不能禁用工作单元 + Transaction opened, unit of work cannot be disabled - {tableTypeFullName} 类型已设置属性 {propertyName} 忽略特性 + The {tableTypeFullName} type has set the property {propertyName} Ignore the attribute - {unitOfWorkManager} 构造参数 {fsql} 不能为 null + The {unitOfWorkManager} constructor parameter {fsql} cannot be null - FreeSql.Repository Update 失败,因为设置了过滤器 {filterKey}: {filterValueExpression},更新的数据不符合{entityString} + FreeSql. Repository Update failed because the filter {filterKey}: {filterValueExpression} is set and the updated data does not conform to {entityString} @@ -780,5 +786,14 @@ + + + 批量注入 Repository,可以参考代码自行调整 + + + + + + diff --git a/FreeSql.DbContext/Properties/DbContextStrings.Designer.cs b/FreeSql.DbContext/Properties/DbContextStrings.Designer.cs index 44a9fd7d1..ff2b54c48 100644 --- a/FreeSql.DbContext/Properties/DbContextStrings.Designer.cs +++ b/FreeSql.DbContext/Properties/DbContextStrings.Designer.cs @@ -4,6 +4,7 @@ using System; using System.Reflection; using System.Resources; +using System.Globalization; using System.Threading; namespace FreeSql @@ -19,8 +20,25 @@ namespace FreeSql /// public static class DbContextStrings { - private static readonly ResourceManager _resourceManager - = new ResourceManager("FreeSql.DbContext.Properties.DbContextStrings", typeof(DbContextStrings).Assembly); + private static readonly ResourceManager _resourceManager = new ResourceManager("FreeSql.DbContext.Properties.DbContextStrings", typeof(DbContextStrings).Assembly); + + private static CultureInfo _resourceCulture; + + /// + /// 重写当前线程的 CurrentUICulture 属性,对 + /// 使用此强类型资源类的所有资源查找执行重写。 + /// + public static CultureInfo Culture + { + get + { + return _resourceCulture; + } + set + { + _resourceCulture = value; + } + } /// /// AddFreeDbContext 发生错误,请检查 {dbContextTypeName} 的构造参数都已正确注入 @@ -344,7 +362,7 @@ public static string UpdateError_Filter(object filterKey, object filterValueExpr private static string GetString(string name, params string[] formatterNames) { - var value = _resourceManager.GetString(name); + var value = _resourceManager.GetString(name,_resourceCulture); for (var i = 0; i < formatterNames.Length; i++) { value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}"); diff --git a/FreeSql.DbContext/Properties/DbContextStrings.en-US.resx b/FreeSql.DbContext/Properties/DbContextStrings.zh-Hans.resx similarity index 70% rename from FreeSql.DbContext/Properties/DbContextStrings.en-US.resx rename to FreeSql.DbContext/Properties/DbContextStrings.zh-Hans.resx index 5b694b09c..ce01210d9 100644 --- a/FreeSql.DbContext/Properties/DbContextStrings.en-US.resx +++ b/FreeSql.DbContext/Properties/DbContextStrings.zh-Hans.resx @@ -118,129 +118,129 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - An error occurred in AddFreeDbContext, check that the construction parameters of {dbContextTypeName} have been injected correctly + AddFreeDbContext 发生错误,请检查 {dbContextTypeName} 的构造参数都已正确注入 - Not addable, already exists in state management: {entityString} + 不可添加,已存在于状态管理:{entityString} - Not addable, entity has no primary key: {entityString} + 不可添加,实体没有主键:{entityString} - Not addable, no value for primary key set: {entityString} + 不可添加,未设置主键的值:{entityString} - Not addable, self-increasing attribute has value: {entityString} + 不可添加,自增属性有值:{entityString} - Not attachable, entity has no primary key: {entityString} + 不可附加,实体没有主键:{entityString} - Not attachable, no value for primary key set: {entityString} + 不可附加,未设置主键的值:{entityString} - Not deletable, data not tracked, should query first: {entityString} + 不可删除,数据未被跟踪,应该先查询:{entityString} - Not deletable, entity has no primary key: {entityString} + 不可删除,实体没有主键:{entityString} - Not deletable, no value for primary key set: {entityString} + 不可删除,未设置主键的值:{entityString} - Not editable, entity has no primary key: {entityString} + 不可进行编辑,实体没有主键:{entityString} - Not updatable, data not tracked, should be queried first or Attach:{entityString} + 不可更新,数据未被跟踪,应该先查询 或者 Attach:{entityString} - Not updatable, entity has no primary key: {entityString} + 不可更新,实体没有主键:{entityString} - Not updatable, no value for primary key set: {entityString} + 不可更新,未设置主键的值:{entityString} - Not updatable, the record does not exist in the database: {entityString} + 不可更新,数据库不存在该记录:{entityString} - Please configure UseFreeSql in OnConfiguring or AddFreeDbContext + 请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql - DbSet. AsType parameter error, please pass in the correct entity type + DbSet.AsType 参数错误,请传入正确的实体类型 - Entity type {EntityTypeName} cannot be converted to {name} and cannot use this method + 实体类型 {EntityTypeName} 无法转换为 {name},无法使用该方法 - Entity type {EntityTypeName} Primary key type is not {fullName} and cannot be used with this method + 实体类型 {EntityTypeName} 主键类型不为 {fullName},无法使用该方法 - Entity type {EntityTypeName} Primary key number is not 1 and cannot be used with this method + 实体类型 {EntityTypeName} 主键数量不为 1,无法使用该方法 - FreeSql. Repository failed to set filter because object does not belong to IRepository + FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository - Not comparable, entity has no primary key: {entityString} + 不可比较,实体没有主键:{entityString} - Non-comparable, no value for primary key set: {entityString} + 不可比较,未设置主键的值:{entityString} - FreeSql. Repository Insert failed because the filter {filterKey}: {filterValueExpression} was set and the inserted data does not conform to {entityString} + FreeSql.Repository Insert 失败,因为设置了过滤器 {filterKey}: {filterValueExpression},插入的数据不符合 {entityString} - ISelect. AsType parameter does not support specifying as object + ISelect.AsType 参数不支持指定为 object - Property {propertyName} does not exist for {tableTypeFullName} + {tableTypeFullName} 不存在属性 {propertyName} - Method DbSet<> not found. StatesRemoveByObjects + 找不到方法 DbSet<>.StatesRemoveByObjects - Parameter data type error {entityTypeFullName} + 参数 data 类型错误 {entityTypeFullName} - Parameter error {param} + 参数错误 {param} - Parameter error {param} cannot be null + 参数错误 {param} 不能为 null - Parameter error {many} is not a collection property + 参数错误 {many} 不是集合属性 - Parameter error {many} Collection property does not exist + 参数错误 {many} 集合属性不存在 - Parameter error {one} attribute does not exist + 参数错误 {one} 属性不存在 - Propagation_ Mandatory: With the current transaction, throw an exception if there is no current transaction + Propagation_Mandatory: 使用当前事务,如果没有当前事务,就抛出异常 - Propagation_ Never: Perform the operation non-transactionally and throw an exception if the current transaction exists + Propagation_Never: 以非事务方式执行操作,如果当前事务存在则抛出异常 - Property {propertyName} of type {tableTypeFullName} is not OneToMany or ManyToMany attribute + {tableTypeFullName} 类型的属性 {propertyName} 不是 OneToMany 或 ManyToMany 特性 - Special error: Bulk add failed, {dataType} returned data, does not match the number added + 特别错误:批量添加失败,{dataType} 的返回数据,与添加的数目不匹配 - Special error: Update failed, data not tracked: {entityString} + 特别错误:更新失败,数据未被跟踪:{entityString} - Transaction opened, unit of work cannot be disabled + 已开启事务,不能禁用工作单元 - The {tableTypeFullName} type has set the property {propertyName} Ignore the attribute + {tableTypeFullName} 类型已设置属性 {propertyName} 忽略特性 - The {unitOfWorkManager} constructor parameter {fsql} cannot be null + {unitOfWorkManager} 构造参数 {fsql} 不能为 null - FreeSql. Repository Update failed because the filter {filterKey}: {filterValueExpression} is set and the updated data does not conform to {entityString} + FreeSql.Repository Update 失败,因为设置了过滤器 {filterKey}: {filterValueExpression},更新的数据不符合{entityString} \ No newline at end of file diff --git a/FreeSql.Tests/FreeSql.Tests/Properties/CoreStringsTests.cs b/FreeSql.Tests/FreeSql.Tests/Properties/CoreStringsTests.cs index d9f547e6b..9c0636229 100644 --- a/FreeSql.Tests/FreeSql.Tests/Properties/CoreStringsTests.cs +++ b/FreeSql.Tests/FreeSql.Tests/Properties/CoreStringsTests.cs @@ -11,20 +11,28 @@ public class CoreStringsTests public CoreStringsTests(ITestOutputHelper output) { this.output = output; - Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); - Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); + //Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("zh-Hans"); + //Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-Hans"); + + //Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); + //Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); + + //CoreStrings.Culture= new System.Globalization.CultureInfo("zh-CN"); + CoreStrings.Culture = new System.Globalization.CultureInfo("en-US"); } [Fact] public void AsTable_PropertyName_NotDateTimeTest() { - string text = CoreStrings.AsTable_PropertyName_NotDateTime("1 "); + var x = CoreStrings.CustomFieldSeparatedBySpaces; + x = CoreStrings.Custom_StaticMethodName_IsNotNull; + string text = CoreStrings.AsTable_PropertyName_NotDateTime("1"); output.WriteLine(text); } [Fact] public void AsTable_PropertyName_FormatErrorTest() { - string text = CoreStrings.AsTable_PropertyName_FormatError("1 "); + string text = CoreStrings.AsTable_PropertyName_FormatError("1"); output.WriteLine(text); } @@ -32,119 +40,119 @@ public void AsTable_PropertyName_FormatErrorTest() [Fact] public void Available_Failed_Get_ResourceTest() { - string text = CoreStrings.Available_Failed_Get_Resource("1", "2 "); + string text = CoreStrings.Available_Failed_Get_Resource("1", "2"); output.WriteLine(text); } [Fact] public void Available_Thrown_ExceptionTest() { - string text = CoreStrings.Available_Thrown_Exception("1 "); + string text = CoreStrings.Available_Thrown_Exception("1"); output.WriteLine(text); } [Fact] public void Bad_Expression_FormatTest() { - string text = CoreStrings.Bad_Expression_Format("1 "); + string text = CoreStrings.Bad_Expression_Format("1"); output.WriteLine(text); } [Fact] public void Cannot_Be_NULL_NameTest() { - string text = CoreStrings.Cannot_Be_NULL_Name("1 "); + string text = CoreStrings.Cannot_Be_NULL_Name("1"); output.WriteLine(text); } [Fact] public void Cannot_Match_PropertyTest() { - string text = CoreStrings.Cannot_Match_Property("1 "); + string text = CoreStrings.Cannot_Match_Property("1"); output.WriteLine(text); } [Fact] public void Cannot_Resolve_ExpressionTreeTest() { - string text = CoreStrings.Cannot_Resolve_ExpressionTree("1 "); + string text = CoreStrings.Cannot_Resolve_ExpressionTree("1"); output.WriteLine(text); } [Fact] public void Custom_Expression_ParsingErrorTest() { - string text = CoreStrings.Custom_Expression_ParsingError("1 "); + string text = CoreStrings.Custom_Expression_ParsingError("1"); output.WriteLine(text); } [Fact] public void Custom_StaticMethodName_NotSet_DynamicFilterCustomTest() { - string text = CoreStrings.Custom_StaticMethodName_NotSet_DynamicFilterCustom("1 "); + string text = CoreStrings.Custom_StaticMethodName_NotSet_DynamicFilterCustom("1"); output.WriteLine(text); } [Fact] public void DataType_AsType_InconsistentTest() { - string text = CoreStrings.DataType_AsType_Inconsistent("1", "2 "); + string text = CoreStrings.DataType_AsType_Inconsistent("1", "2"); output.WriteLine(text); } [Fact] public void DbUpdateVersionException_RowLevelOptimisticLockTest() { - string text = CoreStrings.DbUpdateVersionException_RowLevelOptimisticLock("1", "2 "); + string text = CoreStrings.DbUpdateVersionException_RowLevelOptimisticLock("1", "2"); output.WriteLine(text); } [Fact] public void Duplicate_ColumnAttributeTest() { - string text = CoreStrings.Duplicate_ColumnAttribute("1 "); + string text = CoreStrings.Duplicate_ColumnAttribute("1"); output.WriteLine(text); } [Fact] public void Duplicate_PropertyNameTest() { - string text = CoreStrings.Duplicate_PropertyName("1 "); + string text = CoreStrings.Duplicate_PropertyName("1"); output.WriteLine(text); } [Fact] public void Entity_Must_Primary_KeyTest() { - string text = CoreStrings.Entity_Must_Primary_Key("1", "2 "); + string text = CoreStrings.Entity_Must_Primary_Key("1", "2"); output.WriteLine(text); } [Fact] public void Entity_MySQL_VersionsBelow8_NotSupport_Multiple_PrimaryKeysTest() { - string text = CoreStrings.Entity_MySQL_VersionsBelow8_NotSupport_Multiple_PrimaryKeys("1 "); + string text = CoreStrings.Entity_MySQL_VersionsBelow8_NotSupport_Multiple_PrimaryKeys("1"); output.WriteLine(text); } [Fact] public void Entity_NotParentChild_RelationshipTest() { - string text = CoreStrings.Entity_NotParentChild_Relationship("1 "); + string text = CoreStrings.Entity_NotParentChild_Relationship("1"); output.WriteLine(text); } [Fact] public void Expression_Error_Use_ParameterExpressionTest() { - string text = CoreStrings.Expression_Error_Use_ParameterExpression("1 "); + string text = CoreStrings.Expression_Error_Use_ParameterExpression("1"); output.WriteLine(text); } [Fact] public void Expression_Error_Use_Successive_MemberAccess_TypeTest() { - string text = CoreStrings.Expression_Error_Use_Successive_MemberAccess_Type("1 "); + string text = CoreStrings.Expression_Error_Use_Successive_MemberAccess_Type("1"); output.WriteLine(text); } @@ -158,322 +166,322 @@ public void ExpressionTree_Convert_Type_ErrorTest() [Fact] public void Failed_SubTable_FieldValueTest() { - string text = CoreStrings.Failed_SubTable_FieldValue("1 "); + string text = CoreStrings.Failed_SubTable_FieldValue("1"); output.WriteLine(text); } [Fact] public void Functions_AsTable_NotImplementedTest() { - string text = CoreStrings.Functions_AsTable_NotImplemented("1 "); + string text = CoreStrings.Functions_AsTable_NotImplemented("1"); output.WriteLine(text); } [Fact] public void Generated_Same_SubTableTest() { - string text = CoreStrings.Generated_Same_SubTable("1 "); + string text = CoreStrings.Generated_Same_SubTable("1"); output.WriteLine(text); } [Fact] public void GetPrimarys_ParameterError_IsNotDictKeyTest() { - string text = CoreStrings.GetPrimarys_ParameterError_IsNotDictKey("1 "); + string text = CoreStrings.GetPrimarys_ParameterError_IsNotDictKey("1"); output.WriteLine(text); } [Fact] public void Has_Specified_Cannot_Specified_SecondTest() { - string text = CoreStrings.Has_Specified_Cannot_Specified_Second("1", "2 "); + string text = CoreStrings.Has_Specified_Cannot_Specified_Second("1", "2"); output.WriteLine(text); } [Fact] public void Ignored_Check_Confirm_PublicGetSetTest() { - string text = CoreStrings.Ignored_Check_Confirm_PublicGetSet("1", "2 "); + string text = CoreStrings.Ignored_Check_Confirm_PublicGetSet("1", "2"); output.WriteLine(text); } [Fact] public void IncludeMany_NotValid_NavigationTest() { - string text = CoreStrings.IncludeMany_NotValid_Navigation("1", "2 "); + string text = CoreStrings.IncludeMany_NotValid_Navigation("1", "2"); output.WriteLine(text); } [Fact] public void IncludeMany_ParameterError_OnlyUseOneParameterTest() { - string text = CoreStrings.IncludeMany_ParameterError_OnlyUseOneParameter("1 "); + string text = CoreStrings.IncludeMany_ParameterError_OnlyUseOneParameter("1"); output.WriteLine(text); } [Fact] public void IncludeMany_ParameterError_Select_ReturnConsistentTypeTest() { - string text = CoreStrings.IncludeMany_ParameterError_Select_ReturnConsistentType("1", "2 "); + string text = CoreStrings.IncludeMany_ParameterError_Select_ReturnConsistentType("1", "2"); output.WriteLine(text); } [Fact] public void IncludeMany_ParameterTypeErrorTest() { - string text = CoreStrings.IncludeMany_ParameterTypeError("1 "); + string text = CoreStrings.IncludeMany_ParameterTypeError("1"); output.WriteLine(text); } [Fact] public void InsertInto_No_Property_SelectedTest() { - string text = CoreStrings.InsertInto_No_Property_Selected("1 "); + string text = CoreStrings.InsertInto_No_Property_Selected("1"); output.WriteLine(text); } [Fact] public void InsertInto_TypeErrorTest() { - string text = CoreStrings.InsertInto_TypeError("1 "); + string text = CoreStrings.InsertInto_TypeError("1"); output.WriteLine(text); } [Fact] public void InsertOrUpdate_Must_Primary_KeyTest() { - string text = CoreStrings.InsertOrUpdate_Must_Primary_Key("1 "); + string text = CoreStrings.InsertOrUpdate_Must_Primary_Key("1"); output.WriteLine(text); } [Fact] public void InsertOrUpdate_NotSuport_Generic_UseEntityTest() { - string text = CoreStrings.InsertOrUpdate_NotSuport_Generic_UseEntity("1 "); + string text = CoreStrings.InsertOrUpdate_NotSuport_Generic_UseEntity("1"); output.WriteLine(text); } [Fact] public void LazyLoading_CompilationErrorTest() { - string text = CoreStrings.LazyLoading_CompilationError("1", "2", "2 "); + string text = CoreStrings.LazyLoading_CompilationError("1", "2", "2"); output.WriteLine(text); } [Fact] public void LazyLoading_EntityMustDeclarePublicTest() { - string text = CoreStrings.LazyLoading_EntityMustDeclarePublic("1 "); + string text = CoreStrings.LazyLoading_EntityMustDeclarePublic("1"); output.WriteLine(text); } [Fact] public void ManyToMany_NotFound_CorrespondingFieldTest() { - string text = CoreStrings.ManyToMany_NotFound_CorrespondingField("1", "2", "2", "2", "2 "); + string text = CoreStrings.ManyToMany_NotFound_CorrespondingField("1", "2", "2", "2", "2"); output.WriteLine(text); } [Fact] public void ManyToMany_ParsingError_EntityMissing_PrimaryKeyTest() { - string text = CoreStrings.ManyToMany_ParsingError_EntityMissing_PrimaryKey("1", "2", "2 "); + string text = CoreStrings.ManyToMany_ParsingError_EntityMissing_PrimaryKey("1", "2", "2"); output.WriteLine(text); } [Fact] public void ManyToMany_ParsingError_EntityMustHas_NavigateCollectionTest() { - string text = CoreStrings.ManyToMany_ParsingError_EntityMustHas_NavigateCollection("1", "2", "2 "); + string text = CoreStrings.ManyToMany_ParsingError_EntityMustHas_NavigateCollection("1", "2", "2"); output.WriteLine(text); } [Fact] public void ManyToMany_ParsingError_InconsistentTypeTest() { - string text = CoreStrings.ManyToMany_ParsingError_InconsistentType("1", "2", "2", "2", "2", "2 "); + string text = CoreStrings.ManyToMany_ParsingError_InconsistentType("1", "2", "2", "2", "2", "2"); output.WriteLine(text); } [Fact] public void ManyToMany_ParsingError_IntermediateClass_ErrorMessageTest() { - string text = CoreStrings.ManyToMany_ParsingError_IntermediateClass_ErrorMessage("1", "2", "2", "2", "2 "); + string text = CoreStrings.ManyToMany_ParsingError_IntermediateClass_ErrorMessage("1", "2", "2", "2", "2"); output.WriteLine(text); } [Fact] public void ManyToMany_ParsingError_IntermediateClass_NotManyToOne_OneToOneTest() { - string text = CoreStrings.ManyToMany_ParsingError_IntermediateClass_NotManyToOne_OneToOne("1", "2", "2", "2 "); + string text = CoreStrings.ManyToMany_ParsingError_IntermediateClass_NotManyToOne_OneToOne("1", "2", "2", "2"); output.WriteLine(text); } [Fact] public void Mapping_Exception_HasNo_SamePropertyNameTest() { - string text = CoreStrings.Mapping_Exception_HasNo_SamePropertyName("1 "); + string text = CoreStrings.Mapping_Exception_HasNo_SamePropertyName("1"); output.WriteLine(text); } [Fact] public void Missing_FreeSqlProvider_PackageTest() { - string text = CoreStrings.Missing_FreeSqlProvider_Package("1 "); + string text = CoreStrings.Missing_FreeSqlProvider_Package("1"); output.WriteLine(text); } [Fact] public void Missing_FreeSqlProvider_Package_ReasonTest() { - string text = CoreStrings.Missing_FreeSqlProvider_Package_Reason("1", "2 "); + string text = CoreStrings.Missing_FreeSqlProvider_Package_Reason("1", "2"); output.WriteLine(text); } [Fact] public void Navigation_Bind_Number_DifferentTest() { - string text = CoreStrings.Navigation_Bind_Number_Different("1", "2", "2", "2 "); + string text = CoreStrings.Navigation_Bind_Number_Different("1", "2", "2", "2"); output.WriteLine(text); } [Fact] public void Navigation_Missing_AsSelectTest() { - string text = CoreStrings.Navigation_Missing_AsSelect("1", "2 "); + string text = CoreStrings.Navigation_Missing_AsSelect("1", "2"); output.WriteLine(text); } [Fact] public void Navigation_Missing_SetPropertyTest() { - string text = CoreStrings.Navigation_Missing_SetProperty("1", "2 "); + string text = CoreStrings.Navigation_Missing_SetProperty("1", "2"); output.WriteLine(text); } [Fact] public void Navigation_NotFound_CorrespondingFieldTest() { - string text = CoreStrings.Navigation_NotFound_CorrespondingField("1", "2", "2 "); + string text = CoreStrings.Navigation_NotFound_CorrespondingField("1", "2", "2"); output.WriteLine(text); } [Fact] public void Navigation_ParsingError_EntityMissingPrimaryKeyTest() { - string text = CoreStrings.Navigation_ParsingError_EntityMissingPrimaryKey("1", "2", "2 "); + string text = CoreStrings.Navigation_ParsingError_EntityMissingPrimaryKey("1", "2", "2"); output.WriteLine(text); } [Fact] public void Navigation_ParsingError_InconsistentTypeTest() { - string text = CoreStrings.Navigation_ParsingError_InconsistentType("1", "2", "2", "2", "2", "2 "); + string text = CoreStrings.Navigation_ParsingError_InconsistentType("1", "2", "2", "2", "2", "2"); output.WriteLine(text); } [Fact] public void Navigation_ParsingError_NotFound_PropertyTest() { - string text = CoreStrings.Navigation_ParsingError_NotFound_Property("1", "2", "2", "2 "); + string text = CoreStrings.Navigation_ParsingError_NotFound_Property("1", "2", "2", "2"); output.WriteLine(text); } [Fact] public void NoPrimaryKey_UseSetDtoTest() { - string text = CoreStrings.NoPrimaryKey_UseSetDto("1 "); + string text = CoreStrings.NoPrimaryKey_UseSetDto("1"); output.WriteLine(text); } [Fact] public void Not_Implemented_ExpressionTest() { - string text = CoreStrings.Not_Implemented_Expression("1 "); + string text = CoreStrings.Not_Implemented_Expression("1"); output.WriteLine(text); } [Fact] public void Not_Implemented_Expression_ParameterUseConstantTest() { - string text = CoreStrings.Not_Implemented_Expression_ParameterUseConstant("1", "2 "); + string text = CoreStrings.Not_Implemented_Expression_ParameterUseConstant("1", "2"); output.WriteLine(text); } [Fact] public void Not_Implemented_Expression_UseAsSelectTest() { - string text = CoreStrings.Not_Implemented_Expression_UseAsSelect("1", "2", "2 "); + string text = CoreStrings.Not_Implemented_Expression_UseAsSelect("1", "2", "2"); output.WriteLine(text); } [Fact] public void Not_Implemented_NameTest() { - string text = CoreStrings.Not_Implemented_Name("1 "); + string text = CoreStrings.Not_Implemented_Name("1"); output.WriteLine(text); } [Fact] public void Not_Support_OrderByRandomTest() { - string text = CoreStrings.Not_Support_OrderByRandom("1 "); + string text = CoreStrings.Not_Support_OrderByRandom("1"); output.WriteLine(text); } [Fact] public void Not_Valid_Navigation_PropertyTest() { - string text = CoreStrings.Not_Valid_Navigation_Property("1 "); + string text = CoreStrings.Not_Valid_Navigation_Property("1"); output.WriteLine(text); } [Fact] public void NotFound_ColumnTest() { - string text = CoreStrings.NotFound_Column("1", "2 "); + string text = CoreStrings.NotFound_Column("1", "2"); output.WriteLine(text); } [Fact] public void NotFound_CsName_ColumnTest() { - string text = CoreStrings.NotFound_Column("1", "2 "); + string text = CoreStrings.NotFound_Column("1", "2"); output.WriteLine(text); } [Fact] public void NotFound_PropertyTest() { - string text = CoreStrings.NotFound_Property("1 "); + string text = CoreStrings.NotFound_Property("1"); output.WriteLine(text); } [Fact] public void NotFound_PropertyNameTest() { - string text = CoreStrings.NotFound_PropertyName("1 "); + string text = CoreStrings.NotFound_PropertyName("1"); output.WriteLine(text); } [Fact] public void NotFound_ReflectionTest() { - string text = CoreStrings.NotFound_Reflection("1 "); + string text = CoreStrings.NotFound_Reflection("1"); output.WriteLine(text); } [Fact] public void NotFound_Static_MethodNameTest() { - string text = CoreStrings.NotFound_Static_MethodName("1 "); + string text = CoreStrings.NotFound_Static_MethodName("1"); output.WriteLine(text); } [Fact] public void NotFound_Table_Property_AsTableTest() { - string text = CoreStrings.NotFound_Table_Property_AsTable("1 "); + string text = CoreStrings.NotFound_Table_Property_AsTable("1"); output.WriteLine(text); } @@ -487,119 +495,119 @@ public void ObjectPool_Get_TimeoutTest() [Fact] public void ObjectPool_GetAsync_Queue_LongTest() { - string text = CoreStrings.ObjectPool_GetAsync_Queue_Long("1", "2 "); + string text = CoreStrings.ObjectPool_GetAsync_Queue_Long("1", "2"); output.WriteLine(text); } [Fact] public void OneToMany_NotFound_CorrespondingFieldTest() { - string text = CoreStrings.OneToMany_NotFound_CorrespondingField("1", "2", "2", "2", "2 "); + string text = CoreStrings.OneToMany_NotFound_CorrespondingField("1", "2", "2", "2", "2"); output.WriteLine(text); } [Fact] public void OneToMany_ParsingError_InconsistentTypeTest() { - string text = CoreStrings.OneToMany_ParsingError_InconsistentType("1", "2", "2", "2", "2", "2 "); + string text = CoreStrings.OneToMany_ParsingError_InconsistentType("1", "2", "2", "2", "2", "2"); output.WriteLine(text); } [Fact] public void OneToMany_UseNavigateTest() { - string text = CoreStrings.OneToMany_UseNavigate("1", "2 "); + string text = CoreStrings.OneToMany_UseNavigate("1", "2"); output.WriteLine(text); } [Fact] public void ParameterError_NotValid_CollectionTest() { - string text = CoreStrings.ParameterError_NotValid_Collection("1 "); + string text = CoreStrings.ParameterError_NotValid_Collection("1"); output.WriteLine(text); } [Fact] public void ParameterError_NotValid_NavigationTest() { - string text = CoreStrings.ParameterError_NotValid_Navigation("1 "); + string text = CoreStrings.ParameterError_NotValid_Navigation("1"); output.WriteLine(text); } [Fact] public void ParameterError_NotValid_PropertyNameTest() { - string text = CoreStrings.ParameterError_NotValid_PropertyName("1", "2", "2 "); + string text = CoreStrings.ParameterError_NotValid_PropertyName("1", "2", "2"); output.WriteLine(text); } [Fact] public void ParameterError_NotValid_UseCommasTest() { - string text = CoreStrings.ParameterError_NotValid_UseCommas("1 "); + string text = CoreStrings.ParameterError_NotValid_UseCommas("1"); output.WriteLine(text); } [Fact] public void Parsing_FailedTest() { - string text = CoreStrings.Parsing_Failed("1", "2 "); + string text = CoreStrings.Parsing_Failed("1", "2"); output.WriteLine(text); } [Fact] public void Policy_ObjectPool_DisposeTest() { - string text = CoreStrings.Policy_ObjectPool_Dispose("1 "); + string text = CoreStrings.Policy_ObjectPool_Dispose("1"); output.WriteLine(text); } [Fact] public void Policy_Status_NotAvailableTest() { - string text = CoreStrings.Policy_Status_NotAvailable("1", "2 "); + string text = CoreStrings.Policy_Status_NotAvailable("1", "2"); output.WriteLine(text); } [Fact] public void Properties_AsRowLock_Must_Numeric_ByteTest() { - string text = CoreStrings.Properties_AsRowLock_Must_Numeric_Byte("1 "); + string text = CoreStrings.Properties_AsRowLock_Must_Numeric_Byte("1"); output.WriteLine(text); } [Fact] public void Property_Cannot_FindTest() { - string text = CoreStrings.Property_Cannot_Find("1 "); + string text = CoreStrings.Property_Cannot_Find("1"); output.WriteLine(text); } [Fact] public void Set_Column_IsNullable_FalseTest() { - string text = CoreStrings.Set_Column_IsNullable_False("1 "); + string text = CoreStrings.Set_Column_IsNullable_False("1"); output.WriteLine(text); } [Fact] public void SubTableFieldValue_CannotLessThenTest() { - string text = CoreStrings.SubTableFieldValue_CannotLessThen("1", "2 "); + string text = CoreStrings.SubTableFieldValue_CannotLessThen("1", "2"); output.WriteLine(text); } [Fact] public void SubTableFieldValue_NotConvertDateTimeTest() { - string text = CoreStrings.SubTableFieldValue_NotConvertDateTime("1 "); + string text = CoreStrings.SubTableFieldValue_NotConvertDateTime("1"); output.WriteLine(text); } [Fact] public void SubTableFieldValue_NotMatchTableTest() { - string text = CoreStrings.SubTableFieldValue_NotConvertDateTime("1 "); + string text = CoreStrings.SubTableFieldValue_NotConvertDateTime("1"); output.WriteLine(text); } @@ -607,49 +615,49 @@ public void SubTableFieldValue_NotMatchTableTest() [Fact] public void Type_AsType_Parameter_ErrorTest() { - string text = CoreStrings.Type_AsType_Parameter_Error("1 "); + string text = CoreStrings.Type_AsType_Parameter_Error("1"); output.WriteLine(text); } [Fact] public void Type_Cannot_Access_ConstructorTest() { - string text = CoreStrings.Type_Cannot_Access_Constructor("1 "); + string text = CoreStrings.Type_Cannot_Access_Constructor("1"); output.WriteLine(text); } [Fact] public void Type_Error_NameTest() { - string text = CoreStrings.Type_Error_Name("1 "); + string text = CoreStrings.Type_Error_Name("1"); output.WriteLine(text); } [Fact] public void TypeAsType_NotSupport_ObjectTest() { - string text = CoreStrings.TypeAsType_NotSupport_Object("1 "); + string text = CoreStrings.TypeAsType_NotSupport_Object("1"); output.WriteLine(text); } [Fact] public void TypeError_CannotUse_IncludeManyTest() { - string text = CoreStrings.TypeError_CannotUse_IncludeMany("1 "); + string text = CoreStrings.TypeError_CannotUse_IncludeMany("1"); output.WriteLine(text); } [Fact] public void Unable_Parse_ExpressionTest() { - string text = CoreStrings.Unable_Parse_Expression("1 "); + string text = CoreStrings.Unable_Parse_Expression("1"); output.WriteLine(text); } [Fact] public void Unable_Parse_ExpressionMethodTest() { - string text = CoreStrings.Unable_Parse_ExpressionMethod("1 "); + string text = CoreStrings.Unable_Parse_ExpressionMethod("1"); output.WriteLine(text); } diff --git a/FreeSql.Tests/FreeSql.Tests/Properties/DbContextStringsTests.cs b/FreeSql.Tests/FreeSql.Tests/Properties/DbContextStringsTests.cs index cdfa205cb..aa4d1d240 100644 --- a/FreeSql.Tests/FreeSql.Tests/Properties/DbContextStringsTests.cs +++ b/FreeSql.Tests/FreeSql.Tests/Properties/DbContextStringsTests.cs @@ -15,8 +15,14 @@ public class DbContextStringsTests public DbContextStringsTests(ITestOutputHelper output) { this.output = output; - Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); - Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); + //Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("zh-Hans"); + //Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-Hans"); + + //Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); + //Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); + + //DbContextStrings.Culture= new System.Globalization.CultureInfo("zh-CN"); + DbContextStrings.Culture = new System.Globalization.CultureInfo("en-US"); } [Fact] diff --git a/FreeSql/FreeSql.xml b/FreeSql/FreeSql.xml index 1d32bd1ff..2a07e30b7 100644 --- a/FreeSql/FreeSql.xml +++ b/FreeSql/FreeSql.xml @@ -4603,14 +4603,20 @@ + + + 重写当前线程的 CurrentUICulture 属性,对 + 使用此强类型资源类的所有资源查找执行重写。 + + - [Table(AsTable = "{asTable}")] 特性值格式错误 + [Table(AsTable="{asTable}")] Property value formatted incorrectly - [Table(AsTable = xx)] 设置的属性名 {atmGroupsValue} 不是 DateTime 类型 + The property name {atmGroupsValue} set by [Table (AsTable = xx)] is not of type DateTime @@ -4625,612 +4631,612 @@ - 错误的表达式格式 {column} + Wrong expression format {column} - Chunk 功能之前不可使用 Select + Select is not available until the Chunk function - 安全起见,请务必在事务开启之后,再使用 ForUpdate + For security reasons, be sure to use ForUpdate after the transaction is open - 不能为 null + Cannot be null - {name} 不能为 null + {name} cannot be null - 无法匹配 {property} + Unable to match {property} - {property} 无法解析为表达式树 + {property} cannot be resolved to an expression tree - 参数 masterConnectionString 不可为空,请检查 UseConnectionString + The parameter master ConnectionString cannot be empty, check UseConnectionString - 提交 + Commit - 连接失败,准备切换其他可用服务器 + Connection failed, ready to switch other available servers - 自定义表达式解析错误:类型 {exp3MethodDeclaringType} 需要定义 static ThreadLocal<ExpressionCallContext> 字段、字段、字段(重要三次提醒) + Custom expression parsing error: type {exp3MethodDeclaringType} needs to define static ThreadLocal<ExpressionCallContext>field, field, field (important three reminders) - Custom { 反射信息 }不能为空,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } + Custom {Reflection Information} cannot be empty, format: { static method name }{ space }{ reflection information } - Custom { 静态方法名 }不能为空,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } + Custom { static method name } cannot be empty, format: { static method name }{ space }{ reflection information } - Custom 对应的{{ 静态方法名 }}:{fiValueCustomArray} 未设置 [DynamicFilterCustomAttribute] 特性 + Custom corresponding {{ static method name }}:{fiValueCustomArray} The [DynamicFilterCustomAttribute] attribute is not set - Custom 要求 Field 应该空格分割,并且长度为 2,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } + Custom requires that Fields be space-split and 2-length in the format: { static method name }{ space }{ reflection information } - 操作的数据类型({dataDisplayCsharp}) 与 AsType({tableTypeDisplayCsharp}) 不一致,请检查。 + The data type of the operation ({dataDisplayCsharp}) is inconsistent with AsType ({tableTypeDisplayCsharp}). Please check. - DateRange 要求 Value 应该逗号分割,并且长度为 2 + DateRange requires that Value be comma-separated and 2-length - DateRange 要求 Value[1] 格式必须为:yyyy、yyyy-MM、yyyy-MM-dd、yyyy-MM-dd HH、yyyy、yyyy-MM-dd HH:mm + DateRange requires that the Value [1] format must be: yyyy, yyyy-MM, yyyy-MM-dd, yyyyy-MM-dd HH, yyyy, yyyy-MM-dd HH:mm - 记录可能不存在,或者【行级乐观锁】版本过旧,更新数量{sourceCount},影响的行数{affrows}。 + The record may not exist, or the row level optimistic lock version is out of date, the number of updates {sourceCount}, the number of rows affected {affrows}. - SlaveConnectionString 数量与 SlaveWeights 不相同 + The number of SlaveConnectionStrings is not the same as SlaveWeights - ColumnAttribute.Name {colattrName} 重复存在,请检查(注意:不区分大小写) + ColumnAttribute. Name {colattrName} exists repeatedly, please check (note: case insensitive) - 属性名 {pName} 重复存在,请检查(注意:不区分大小写) + Property name {pName} exists repeatedly, please check (note: case insensitive) - {function} 功能要求实体类 {tableCsName} 必须有主键 + The {function} feature requires that the entity class {tableCsName} must have a primary key - {tbTypeFullName} 是父子关系,但是 MySql 8.0 以下版本中不支持组合多主键 + {tbTypeFullName} is a parent-child relationship, but combinations of multiple primary keys are not supported in versions below MySql 8.0 - {tbTypeFullName} 不是父子关系,无法使用该功能 + {tbTypeFullName} is not a parent-child relationship and cannot be used - 这个特别的子查询不能解析 + This particular subquery cannot be resolved - 表达式错误,它的顶级对象不是 ParameterExpression:{exp} + Expression error, its top object is not ParameterExpression:{exp} - 表达式错误,它不是连续的 MemberAccess 类型:{exp} + Expression error, it is not a continuous MemberAccess type: {exp} - ExpressionTree 转换类型错误,值({value}),类型({valueTypeFullName}),目标类型({typeFullName}),{exMessage} + ExpressionTree conversion type error, value ({value}), type ({valueTypeFullName}), target type ({typeFullName}), Error:{exMessage} - 未能解析分表字段值 {sqlWhere} + Failed to parse table field value {sqlWhere} - AsTable 未实现的功能 {asTable} + Function {asTable} not implemented by AsTable - GBase 暂时不支持逗号以外的分割符 + GBase does not support separators other than commas at this time - tableName:{tableName} 生成了相同的分表名 + TableName:{tableName} generated the same table name - GetPrimarys 传递的参数 "{primary}" 不正确,它不属于字典数据的键名 + The parameter'{primary}'passed by GetPrimarys is incorrect and does not belong to the key name of the dictionary data - 已经指定了 {first},不能再指定 {second} + {first} has already been specified and {second} can no longer be specified - {tb2DbName}.{mp2MemberName} 被忽略,请检查 IsIgnore 设置,确认 get/set 为 public + {tb2DbName}. {mp2MemberName} is ignored. Check the IsIgnore setting to make sure get/set is public - Include 参数类型错误 + Include parameter type error - Include 参数类型错误,集合属性请使用 IncludeMany + Include parameter type is wrong, use IncludeMany for collection properties - Include 参数类型错误,表达式类型应该为 MemberAccess + Include parameter type is wrong, expression type should be MemberAccess - IncludeMany 类型 {tbTypeDisplayCsharp} 的属性 {collMemMemberName} 不是有效的导航属性,提示:IsIgnore = true 不会成为导航属性 + The property {collMemMemberName} of IncludeMany type {tbTypeDisplayCsharp} is not a valid navigation property, hint: IsIgnore = true will not be a navigation property - IncludeMany {navigateSelector} 参数错误,Select 只可以使用一个参数的方法,正确格式:.Select(t =>new TNavigate {{}}) + IncludeMany {navigateSelector} parameter is wrong, Select can only use one parameter's method, the correct format:.Select(t =>new TNavigate{{}}) - IncludeMany {navigateSelector} 参数错误,Select lambda参数返回值必须和 {collMemElementType} 类型一致 + IncludeMany {navigateSelector} parameter error, Select lambda parameter return value must match {collMemElementType} type - IncludeMany 参数1 类型错误,表达式类型应该为 MemberAccess + IncludeMany parameter 1 has wrong type, expression type should be MemberAccess - IncludeMany {navigateSelector} 参数类型错误,正确格式: a.collections.Take(1).Where(c =>c.aid == a.id).Select(a=> new TNavigate{{}}) + IncludeMany {navigateSelector} parameter type is wrong, correct format: a.collections.Take(1).Where(c => C.A ID == a.id).Select (a => new TNavigate{{}}) - ISelect.InsertInto() 未选择属性: {displayCsharp} + ISelect. InsertInto() did not select an attribute: {displayCsharp} - ISelect.InsertInto() 类型错误: {displayCsharp} + ISelect. InsertInto() type error: {displayCsharp} - InsertOrUpdate 功能执行 merge into 要求实体类 {CsName} 必须有主键 + The InsertOrUpdate function performs merge into requiring the entity class {CsName} to have a primary key - InsertOrUpdate<>的泛型参数 不支持 {typeofT1},请传递您的实体类 + The generic parameter for InsertOrUpdate<>does not support {typeofT1}. Pass in your entity class - 【延时加载】功能需要安装 FreeSql.Extensions.LazyLoading.dll,可前往 nuget 下载 + FreeSql needs to be installed for Delayed Loading. Extensions. LazyLoading. Dll, downloadable to nuget - 【延时加载】{trytbTypeName} 编译错误:{exMessage}\r\n\r\n{cscode} + {trytbTypeName} Compilation error: {exMessage}\r\n\r\n{cscode} - 【延时加载】实体类型 {trytbTypeName} 必须声明为 public + Entity type {trytbTypeName} must be declared public - ManyToMany 导航属性 .AsSelect() 暂时不可用于 Sum/Avg/Max/Min/First/ToOne/ToList 方法 + ManyToMany navigation properties. AsSelect() is temporarily unavailable for the Sum/Avg/Max/Min/First/ToOne/ToList method - 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 在 {tbmidCsName} 中没有找到对应的字段,如:{midTypePropsTrytbName}{findtrytbPkCsName}、{midTypePropsTrytbName}_{findtrytbPkCsName} + [ManyToMany] Navigation property {trytbTypeName}. {pnvName} did not find a corresponding field in {tbmidCsName}, such as: {midTypePropsTrytbName}{findtrytbPkCsName}, {midTypePropsTrytbName}_ {findtrytbPkCsName} - 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {tbrefTypeName} 缺少主键标识,[Column(IsPrimary = true)] + [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, entity type {tbrefTypeName} missing primary key identity, [Column (IsPrimary = true)] - 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {tbrefTypeName} 必须存在对应的 [Navigate(ManyToMany = x)] 集合属性 + [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, entity type {tbrefTypeName} must have a corresponding [Navigate (ManyToMany = x)] collection property - 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,{tbmidCsName}.{trycolCsName} 和 {trytbCsName}.{trytbPrimarysCsName} 类型不一致 + [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, {tbmidCsName}. {trycolCsName} and {trytbCsName}. {trytbPrimarysCsName} type inconsistent - 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,中间类 {tbmidCsName}.{midTypePropsTrytbName} 错误:{exMessage} + [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, intermediate class {tbmidCsName}.{midTypePropsTrytbName} Error: {exMessage} - 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,中间类 {tbmidCsName}.{midTypePropsTrytbName} 导航属性不是【ManyToOne】或【OneToOne】 + [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, intermediate class {tbmidCsName}. The {midTypePropsTrytbName} navigation property is not ManyToOne or OneToOne - 映射异常:{name} 没有一个属性名相同 + Mapping exception: {name} None of the property names are the same - Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决 + Ado. MasterPool value is null, this operation cannot self-enable transactions, please explicitly pass [transaction object] resolution - 缺少 FreeSql 数据库实现包:FreeSql.Provider.{Provider}.dll,可前往 nuget 下载 + Missing FreeSql database implementation package: FreeSql. Provider. {Provider}. Dll, downloadable to nuget - 缺少 FreeSql 数据库实现包:{dll},可前往 nuget 下载;如果存在 {dll} 依然报错(原因是环境问题导致反射不到类型),请在 UseConnectionString/UseConnectionFactory 第三个参数手工传入 typeof({providerType}) + The FreeSql database implementation package is missing: {dll} can be downloaded to nuget; If there is {dll} and an error still occurs (due to environmental issues that cause the type to be unreflected), manually pass in typeof ({providerType}) in the third parameter of UseConnectionString/UseConnectionFactory - 导航属性 {trytbTypeName}.{pnvName} 特性 [Navigate] Bind 数目({bindColumnsCount}) 与 外部主键数目({tbrefPrimarysLength}) 不相同 + Navigation property {trytbTypeName}. The number of {pnvName} attributes [Navigate] Binds ({bindColumnsCount}) is different from the number of external primary keys ({tbrefPrimarysLength}) - {tb2DbName}.{mp2MemberName} 导航属性集合忘了 .AsSelect() 吗?如果在 ToList(a => a.{mp2MemberName}) 中使用,请移步参考 IncludeMany 文档。 + {tb2DbName}. {mp2MemberName} Navigation Property Collection forgotten. AsSelect()? If used in ToList (a => a. {mp2MemberName}), step by step to refer to the IncludeMany document. - 【导航属性】{trytbTypeDisplayCsharp}.{pName} 缺少 set 属性 + [Navigation Properties]{trytbTypeDisplayCsharp}. Missing set attribute for {pName} - 导航属性 {trytbTypeName}.{pnvName} 没有找到对应的字段,如:{pnvName}{findtbrefPkCsName}、{pnvName}_{findtbrefPkCsName}。或者使用 [Navigate] 特性指定关系映射。 + Navigation property {trytbTypeName}. {pnvName} No corresponding fields were found, such as: {pnvName}{findtbrefPkCsName}, {pnvName}_ {findtbrefPkCsName}. Or use the [Navigate] attribute to specify the relationship mapping. - 导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {trytcTypeName} 缺少主键标识,[Column(IsPrimary = true)] + Navigation property {trytbTypeName}. {pnvName} parsing error, entity type {trytcTypeName} missing primary key identity, [Column (IsPrimary = true)] - 导航属性 {trytbTypeName}.{pnvName} 解析错误,{trytbCsName}.{trycolCsName} 和 {tbrefCsName}.{tbrefPrimarysCsName} 类型不一致 + Navigation property {trytbTypeName}. {pnvName} parsing error, {trytbCsName}. {trycolCsName} and {tbrefCsName}. {tbrefPrimarysCsName} type inconsistent - 导航属性 {trytbTypeName}.{pnvName} 特性 [Navigate] 解析错误,在 {tbrefTypeName} 未找到属性:{bi} + Navigation property {trytbTypeName}. {pnvName} attribute [Navigate] parsing error, property not found at {tbrefTypeName}: {bi} - {tableTypeDisplayCsharp} 没有定义主键,无法使用 SetSource,请尝试 SetDto + {tableTypeDisplayCsharp} has no primary key defined and cannot use SetSource. Try SetDto or SetSource to specify a temporary primary key - 没有定义属性 + No properties defined - 未实现 + Not implemented - 未实现函数表达式 {exp} 解析 + Function expression {exp} parsing not implemented - 未实现函数表达式 {exp} 解析,参数 {expArguments} 必须为常量 + Function expression {exp} parsing not implemented, parameter {expArguments} must be constant - 未实现函数表达式 {exp} 解析,如果正在操作导航属性集合,请使用 .AsSelect().{exp3MethodName}({exp3ArgumentsCount}) + Function expression {exp} parsing is not implemented. Use if you are working on a navigation property collection. AsSelect (). {exp3MethodName} ({exp3ArgumentsCount}) - 未实现 MemberAccess 下的 Constant + Constant under MemberAccess is not implemented - 未实现 {name} + {name} is not implemented - 不支持 + I won't support it - {dataType} 不支持 OrderByRandom 随机排序 + {dataType} does not support OrderByRandom sorting - {property} 不是有效的导航属性 + {property} is not a valid navigation property - {dbName} 找不到列 {memberName} + {dbName} Column {memberName} not found - 找不到 {CsName} 对应的列 + Cannot find the column corresponding to {CsName} - 找不到属性:{memberName} + Attribute not found: {memberName} - 找不到属性名 {proto} + Property name {proto} not found - Custom 找不到对应的{{ 反射信息 }}:{fiValueCustomArray} + Custom could not find the corresponding {{ reflection information }}:{fiValueCustomArray} - Custom 找不到对应的{{ 静态方法名 }}:{fiValueCustomArray} + Custom could not find the corresponding {{ static method name }}:{fiValueCustomArray} - [Table(AsTable = xx)] 设置的属性名 {atmGroupsValue} 不存在 + The property name {atmGroupsValue} set by [Table(AsTable = xx)] does not exist - 未指定 UseConnectionString 或者 UseConnectionFactory + No UseConnectionString or UseConnectionFactory specified - 【{policyName}】ObjectPool.{GetName}() timeout {totalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081 + [{policyName}] ObjectPool. {GetName}() timeout {totalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081 - 【{policyName}】ObjectPool.GetAsync() The queue is too long. Policy.AsyncGetCapacity = {asyncGetCapacity} + [{policyName}] ObjectPool. GetAsync() The queue is too long. Policy. AsyncGetCapacity = {asyncGetCapacity} - 【OneToMany】导航属性 {trytbTypeName}.{pnvName} 在 {tbrefCsName} 中没有找到对应的字段,如:{findtrytb}{findtrytbPkCsName}、{findtrytb}_{findtrytbPkCsName} + [OneToMany] Navigation property {trytbTypeName}.{pnvName} did not find a corresponding field in {tbrefCsName}, such as: {findtrytb}{findtrytbPkCsName}, {findtrytb}_{findtrytbPkCsName} - 【OneToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,{trytbCsName}.{trytbPrimarysCsName} 和 {tbrefCsName}.{trycolCsName} 类型不一致 + [OneToMany] Navigation property {trytbTypeName}.{pnvName} parsing error, {trytbCsName}.{trytbPrimarysCsName} and {tbrefCsName}.{trycolCsName} is of inconsistent type - 、{refpropName}{findtrytbPkCsName}、{refpropName}_{findtrytbPkCsName}。或者使用 [Navigate] 特性指定关系映射。 + , {refpropName}{findtrytbPkCsName}, {refpropName}_{findtrytbPkCsName}. Or use the [Navigate] attribute to specify the relationship mapping. - 参数 field 未指定 + Parameter field not specified - {property} 参数错误,它不是集合属性,必须为 IList<T> 或者 ICollection<T> + The {property} parameter is incorrect, it is not a collection property and must be IList<T>or ICollection<T> - {property} 参数错误,它不是有效的导航属性 + The {property} parameter is incorrect, it is not a valid navigation property - {where} 参数错误,{keyval} 不是有效的属性名,在实体类 {reftbTypeDisplayCsharp} 无法找到 + {where} parameter error, {keyval} is not a valid property name and cannot be found in entity class {reftbTypeDisplayCsharp} - {property} 参数错误,格式 "TopicId=Id,多组使用逗号连接" + {property} parameter error, format "TopicId=Id, multiple groups using comma connection" - 解析失败 {callExpMethodName} {message} + Parsing failed {callExpMethodName} {message} - 【{policyName}】The ObjectPool has been disposed, see: https://github.com/dotnetcore/FreeSql/discussions/1079 + [{policyName}] The ObjectPool has been disposed, see: https://github.com/dotnetcore/FreeSql/discussions/1079 - 【{policyName}】状态不可用,等待后台检查程序恢复方可使用。{UnavailableExceptionMessage} + The {policyName} status is unavailable and cannot be used until the background checker is restored. {UnavailableExceptionMessage} - 属性{trytbVersionColumnCsName} 被标注为行锁(乐观锁)(IsVersion),但其必须为数字类型 或者 byte[],并且不可为 Nullable + The property {trytbVersionColumnCsName} is labeled as a row lock (optimistic lock) (IsVersion), but it must be a numeric type or byte[], and it cannot be Nullable - properties 参数不能为空 + Properrties parameter cannot be empty - {property} 属性名无法找到 + {property} property name not found - Range 要求 Value 应该逗号分割,并且长度为 2 + Range requires that Value be comma-separated and 2-length - 回滚 + RollBack - 运行时错误,反射获取 IncludeMany 方法失败 + Runtime error, reflection failed to get IncludeMany method - {qoteSql} is NULL,除非设置特性 [Column(IsNullable = false)] + {qoteSql} is NULL unless the attribute [Column (IsNullable = false)] - 分表字段值 "{dt}" 不能小于 "{beginTime} " + Subtable field value'{dt}'cannot be less than'{beginTime}' - 分表字段值不能为 null + Subtable field value cannot be null - 分表字段值 "{columnValue}" 不能转化成 DateTime + The tabular field value'{columnValue}'cannot be converted to DateTime - 分表字段值 "{dt}" 未匹配到分表名 + Table field value'{dt}'does not match table name - T2 类型错误 + Type T2 Error - tableName 格式错误,示例:“log_{yyyyMMdd}” + TableName format error, example: "log_{yyyyMMdd}" - {Type}.AsType 参数错误,请传入正确的实体类型 + {Type}. AsType parameter error, please pass in the correct entity type - {thatFullName} 类型无法访问构造函数 + The {thatFullName} type cannot access the constructor - {name} 类型错误 + {name} type error - {Type}.AsType 参数不支持指定为 object + {Type}. AsType parameter does not support specifying as object - 类型 {typeofFullName} 错误,不能使用 IncludeMany + Type {typeofFullName} error, IncludeMany cannot be used - 无法解析表达式:{exp} + Unable to parse expression: {exp} - 无法解析表达式方法 {exp3tmpCallMethodName} + Unable to parse expression method {exp3tmpCallMethodName} - 请使用 fsql.InsertDict(dict) 方法插入字典数据 + Please use fsql. InsertDict (dict) method inserts dictionary data diff --git a/FreeSql/Properties/CoreStrings.Designer.cs b/FreeSql/Properties/CoreStrings.Designer.cs index 342086681..f5d53c6bb 100644 --- a/FreeSql/Properties/CoreStrings.Designer.cs +++ b/FreeSql/Properties/CoreStrings.Designer.cs @@ -4,6 +4,7 @@ using System; using System.Reflection; using System.Resources; +using System.Globalization; using System.Threading; namespace FreeSql @@ -19,8 +20,25 @@ namespace FreeSql /// public static class CoreStrings { - private static readonly ResourceManager _resourceManager - = new ResourceManager("FreeSql.Properties.CoreStrings", typeof(CoreStrings).Assembly); + private static readonly ResourceManager _resourceManager = new ResourceManager("FreeSql.Properties.CoreStrings", typeof(CoreStrings).Assembly); + + private static CultureInfo _resourceCulture; + + /// + /// 重写当前线程的 CurrentUICulture 属性,对 + /// 使用此强类型资源类的所有资源查找执行重写。 + /// + public static CultureInfo Culture + { + get + { + return _resourceCulture; + } + set + { + _resourceCulture = value; + } + } /// /// [Table(AsTable = "{asTable}")] 特性值格式错误 @@ -565,7 +583,7 @@ public static string Navigation_ParsingError_NotFound_Property(object trytbTypeN trytbTypeName, pnvName, tbrefTypeName, bi); /// - /// {tableTypeDisplayCsharp} 没有定义主键,无法使用 SetSource,请尝试 SetDto + /// {tableTypeDisplayCsharp} 没有定义主键,无法使用 SetSource,请尝试 SetDto 或者 SetSource 指定临时主键 /// public static string NoPrimaryKey_UseSetDto(object tableTypeDisplayCsharp) => string.Format( @@ -964,7 +982,7 @@ public static string Use_InsertDict_Method private static string GetString(string name, params string[] formatterNames) { - var value = _resourceManager.GetString(name); + var value = _resourceManager.GetString(name,_resourceCulture); for (var i = 0; i < formatterNames.Length; i++) { value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}"); diff --git a/FreeSql/Properties/CoreStrings.en-US.resx b/FreeSql/Properties/CoreStrings.zh-Hans.resx similarity index 54% rename from FreeSql/Properties/CoreStrings.en-US.resx rename to FreeSql/Properties/CoreStrings.zh-Hans.resx index 29eae3a71..d7036cb33 100644 --- a/FreeSql/Properties/CoreStrings.en-US.resx +++ b/FreeSql/Properties/CoreStrings.zh-Hans.resx @@ -118,10 +118,10 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - [Table(AsTable="{asTable}")] Property value formatted incorrectly + [Table(AsTable = "{asTable}")] 特性值格式错误 - The property name {atmGroupsValue} set by [Table (AsTable = xx)] is not of type DateTime + [Table(AsTable = xx)] 设置的属性名 {atmGroupsValue} 不是 DateTime 类型 {name}: Failed to get resource {statistics} @@ -130,369 +130,369 @@ {name}: An exception needs to be thrown - Wrong expression format {column} + 错误的表达式格式 {column} - Select is not available until the Chunk function + Chunk 功能之前不可使用 Select - For security reasons, be sure to use ForUpdate after the transaction is open + 安全起见,请务必在事务开启之后,再使用 ForUpdate - Cannot be null + 不能为 null - {name} cannot be null + {name} 不能为 null - Unable to match {property} + 无法匹配 {property} - {property} cannot be resolved to an expression tree + {property} 无法解析为表达式树 - The parameter master ConnectionString cannot be empty, check UseConnectionString + 参数 masterConnectionString 不可为空,请检查 UseConnectionString - Commit + 提交 - Connection failed, ready to switch other available servers + 连接失败,准备切换其他可用服务器 - Custom expression parsing error: type {exp3MethodDeclaringType} needs to define static ThreadLocal<ExpressionCallContext>field, field, field (important three reminders) + 自定义表达式解析错误:类型 {exp3MethodDeclaringType} 需要定义 static ThreadLocal<ExpressionCallContext> 字段、字段、字段(重要三次提醒) - Custom {Reflection Information} cannot be empty, format: {static method name}{space}{reflection information} + Custom { 反射信息 }不能为空,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } - Custom {static method name} cannot be empty, format: {static method name}{space}{reflection information} + Custom { 静态方法名 }不能为空,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } - Custom corresponding {{static method name}}:{fiValueCustomArray} The [DynamicFilterCustomAttribute] attribute is not set + Custom 对应的{{ 静态方法名 }}:{fiValueCustomArray} 未设置 [DynamicFilterCustomAttribute] 特性 - Custom requires that Fields be space-split and 2-length in the format: {static method name}{space}{reflection information} + Custom 要求 Field 应该空格分割,并且长度为 2,格式:{ 静态方法名 }{ 空格 }{ 反射信息 } - The data type of the operation ({dataDisplayCsharp}) is inconsistent with AsType ({tableTypeDisplayCsharp}). Please check. + 操作的数据类型({dataDisplayCsharp}) 与 AsType({tableTypeDisplayCsharp}) 不一致,请检查。 - DateRange requires that Value be comma-separated and 2-length + DateRange 要求 Value 应该逗号分割,并且长度为 2 - DateRange requires that the Value [1] format must be: yyyy, yyyy-MM, yyyy-MM-dd, yyyyy-MM-dd HH, yyyy, yyyy-MM-dd HH:mm + DateRange 要求 Value[1] 格式必须为:yyyy、yyyy-MM、yyyy-MM-dd、yyyy-MM-dd HH、yyyy、yyyy-MM-dd HH:mm - The record may not exist, or the row level optimistic lock version is out of date, the number of updates {sourceCount}, the number of rows affected {affrows}. + 记录可能不存在,或者【行级乐观锁】版本过旧,更新数量{sourceCount},影响的行数{affrows}。 - The number of SlaveConnectionStrings is not the same as SlaveWeights + SlaveConnectionString 数量与 SlaveWeights 不相同 - ColumnAttribute. Name {colattrName} exists repeatedly, please check (note: case insensitive) + ColumnAttribute.Name {colattrName} 重复存在,请检查(注意:不区分大小写) - Property name {pName} exists repeatedly, please check (note: case insensitive) + 属性名 {pName} 重复存在,请检查(注意:不区分大小写) - The {function} feature requires that the entity class {tableCsName} must have a primary key + {function} 功能要求实体类 {tableCsName} 必须有主键 - {tbTypeFullName} is a parent-child relationship, but combinations of multiple primary keys are not supported in versions below MySql 8.0 + {tbTypeFullName} 是父子关系,但是 MySql 8.0 以下版本中不支持组合多主键 - {tbTypeFullName} is not a parent-child relationship and cannot be used + {tbTypeFullName} 不是父子关系,无法使用该功能 - This particular subquery cannot be resolved + 这个特别的子查询不能解析 - Expression error, its top object is not ParameterExpression:{exp} + 表达式错误,它的顶级对象不是 ParameterExpression:{exp} - Expression error, it is not a continuous MemberAccess type: {exp} + 表达式错误,它不是连续的 MemberAccess 类型:{exp} - ExpressionTree conversion type error, value ({value}), type ({valueTypeFullName}), target type ({typeFullName}), Error:{exMessage} + ExpressionTree 转换类型错误,值({value}),类型({valueTypeFullName}),目标类型({typeFullName}),{exMessage} - Failed to parse table field value {sqlWhere} + 未能解析分表字段值 {sqlWhere} - Function {asTable} not implemented by AsTable + AsTable 未实现的功能 {asTable} - GBase does not support separators other than commas at this time + GBase 暂时不支持逗号以外的分割符 - TableName:{tableName} generated the same table name + tableName:{tableName} 生成了相同的分表名 - The parameter'{primary}'passed by GetPrimarys is incorrect and does not belong to the key name of the dictionary data + GetPrimarys 传递的参数 "{primary}" 不正确,它不属于字典数据的键名 - {first} has already been specified and {second} can no longer be specified + 已经指定了 {first},不能再指定 {second} - {tb2DbName}. {mp2MemberName} is ignored. Check the IsIgnore setting to make sure get/set is public + {tb2DbName}.{mp2MemberName} 被忽略,请检查 IsIgnore 设置,确认 get/set 为 public - Include parameter type error + Include 参数类型错误 - Include parameter type is wrong, use IncludeMany for collection properties + Include 参数类型错误,集合属性请使用 IncludeMany - Include parameter type is wrong, expression type should be MemberAccess + Include 参数类型错误,表达式类型应该为 MemberAccess - The property {collMemMemberName} of IncludeMany type {tbTypeDisplayCsharp} is not a valid navigation property, hint: IsIgnore = true will not be a navigation property + IncludeMany 类型 {tbTypeDisplayCsharp} 的属性 {collMemMemberName} 不是有效的导航属性,提示:IsIgnore = true 不会成为导航属性 - IncludeMany {navigateSelector} parameter is wrong, Select can only use one parameter's method, the correct format:.Select(t =>new TNavigate{{}}) + IncludeMany {navigateSelector} 参数错误,Select 只可以使用一个参数的方法,正确格式:.Select(t =>new TNavigate {{}}) - IncludeMany {navigateSelector} parameter error, Select lambda parameter return value must match {collMemElementType} type + IncludeMany {navigateSelector} 参数错误,Select lambda参数返回值必须和 {collMemElementType} 类型一致 - IncludeMany parameter 1 has wrong type, expression type should be MemberAccess + IncludeMany 参数1 类型错误,表达式类型应该为 MemberAccess - IncludeMany {navigateSelector} parameter type is wrong, correct format: a.collections.Take(1).Where(c => C.A ID == a.id).Select (a => new TNavigate{{}}) + IncludeMany {navigateSelector} 参数类型错误,正确格式: a.collections.Take(1).Where(c =>c.aid == a.id).Select(a=> new TNavigate{{}}) - ISelect. InsertInto() did not select an attribute: {displayCsharp} + ISelect.InsertInto() 未选择属性: {displayCsharp} - ISelect. InsertInto() type error: {displayCsharp} + ISelect.InsertInto() 类型错误: {displayCsharp} - The InsertOrUpdate function performs merge into requiring the entity class {CsName} to have a primary key + InsertOrUpdate 功能执行 merge into 要求实体类 {CsName} 必须有主键 - The generic parameter for InsertOrUpdate<>does not support {typeofT1}. Pass in your entity class + InsertOrUpdate<>的泛型参数 不支持 {typeofT1},请传递您的实体类 - FreeSql needs to be installed for Delayed Loading. Extensions. LazyLoading. Dll, downloadable to nuget + 【延时加载】功能需要安装 FreeSql.Extensions.LazyLoading.dll,可前往 nuget 下载 - {trytbTypeName} Compilation error: {exMessage}\r\n\r\n{cscode} + 【延时加载】{trytbTypeName} 编译错误:{exMessage}\r\n\r\n{cscode} - Entity type {trytbTypeName} must be declared public + 【延时加载】实体类型 {trytbTypeName} 必须声明为 public - ManyToMany navigation properties. AsSelect() is temporarily unavailable for the Sum/Avg/Max/Min/First/ToOne/ToList method + ManyToMany 导航属性 .AsSelect() 暂时不可用于 Sum/Avg/Max/Min/First/ToOne/ToList 方法 - [ManyToMany] Navigation property {trytbTypeName}. {pnvName} did not find a corresponding field in {tbmidCsName}, such as: {midTypePropsTrytbName}{findtrytbPkCsName}, {midTypePropsTrytbName}_ {findtrytbPkCsName} + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 在 {tbmidCsName} 中没有找到对应的字段,如:{midTypePropsTrytbName}{findtrytbPkCsName}、{midTypePropsTrytbName}_{findtrytbPkCsName} - [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, entity type {tbrefTypeName} missing primary key identity, [Column (IsPrimary = true)] + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {tbrefTypeName} 缺少主键标识,[Column(IsPrimary = true)] - [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, entity type {tbrefTypeName} must have a corresponding [Navigate (ManyToMany = x)] collection property + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {tbrefTypeName} 必须存在对应的 [Navigate(ManyToMany = x)] 集合属性 - [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, {tbmidCsName}. {trycolCsName} and {trytbCsName}. {trytbPrimarysCsName} type inconsistent + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,{tbmidCsName}.{trycolCsName} 和 {trytbCsName}.{trytbPrimarysCsName} 类型不一致 - [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, intermediate class {tbmidCsName}.{midTypePropsTrytbName} Error: {exMessage} + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,中间类 {tbmidCsName}.{midTypePropsTrytbName} 错误:{exMessage} - [ManyToMany] Navigation property {trytbTypeName}. {pnvName} parsing error, intermediate class {tbmidCsName}. The {midTypePropsTrytbName} navigation property is not ManyToOne or OneToOne + 【ManyToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,中间类 {tbmidCsName}.{midTypePropsTrytbName} 导航属性不是【ManyToOne】或【OneToOne】 - Mapping exception: {name} None of the property names are the same + 映射异常:{name} 没有一个属性名相同 - Ado. MasterPool value is null, this operation cannot self-enable transactions, please explicitly pass [transaction object] resolution + Ado.MasterPool 值为 null,该操作无法自启用事务,请显式传递【事务对象】解决 - Missing FreeSql database implementation package: FreeSql. Provider. {Provider}. Dll, downloadable to nuget + 缺少 FreeSql 数据库实现包:FreeSql.Provider.{Provider}.dll,可前往 nuget 下载 - The FreeSql database implementation package is missing: {dll} can be downloaded to nuget; If there is {dll} and an error still occurs (due to environmental issues that cause the type to be unreflected), manually pass in typeof ({providerType}) in the third parameter of UseConnectionString/UseConnectionFactory + 缺少 FreeSql 数据库实现包:{dll},可前往 nuget 下载;如果存在 {dll} 依然报错(原因是环境问题导致反射不到类型),请在 UseConnectionString/UseConnectionFactory 第三个参数手工传入 typeof({providerType}) - Navigation property {trytbTypeName}. The number of {pnvName} attributes [Navigate] Binds ({bindColumnsCount}) is different from the number of external primary keys ({tbrefPrimarysLength}) + 导航属性 {trytbTypeName}.{pnvName} 特性 [Navigate] Bind 数目({bindColumnsCount}) 与 外部主键数目({tbrefPrimarysLength}) 不相同 - {tb2DbName}. {mp2MemberName} Navigation Property Collection forgotten. AsSelect()? If used in ToList (a => a. {mp2MemberName}), step by step to refer to the IncludeMany document. + {tb2DbName}.{mp2MemberName} 导航属性集合忘了 .AsSelect() 吗?如果在 ToList(a => a.{mp2MemberName}) 中使用,请移步参考 IncludeMany 文档。 - [Navigation Properties]{trytbTypeDisplayCsharp}. Missing set attribute for {pName} + 【导航属性】{trytbTypeDisplayCsharp}.{pName} 缺少 set 属性 - Navigation property {trytbTypeName}. {pnvName} No corresponding fields were found, such as: {pnvName}{findtbrefPkCsName}, {pnvName}_ {findtbrefPkCsName}. Or use the [Navigate] attribute to specify the relationship mapping. + 导航属性 {trytbTypeName}.{pnvName} 没有找到对应的字段,如:{pnvName}{findtbrefPkCsName}、{pnvName}_{findtbrefPkCsName}。或者使用 [Navigate] 特性指定关系映射。 - Navigation property {trytbTypeName}. {pnvName} parsing error, entity type {trytcTypeName} missing primary key identity, [Column (IsPrimary = true)] + 导航属性 {trytbTypeName}.{pnvName} 解析错误,实体类型 {trytcTypeName} 缺少主键标识,[Column(IsPrimary = true)] - Navigation property {trytbTypeName}. {pnvName} parsing error, {trytbCsName}. {trycolCsName} and {tbrefCsName}. {tbrefPrimarysCsName} type inconsistent + 导航属性 {trytbTypeName}.{pnvName} 解析错误,{trytbCsName}.{trycolCsName} 和 {tbrefCsName}.{tbrefPrimarysCsName} 类型不一致 - Navigation property {trytbTypeName}. {pnvName} attribute [Navigate] parsing error, property not found at {tbrefTypeName}: {bi} + 导航属性 {trytbTypeName}.{pnvName} 特性 [Navigate] 解析错误,在 {tbrefTypeName} 未找到属性:{bi} - {tableTypeDisplayCsharp} has no primary key defined and cannot use SetSource. Try SetDto or SetSource to specify a temporary primary key + {tableTypeDisplayCsharp} 没有定义主键,无法使用 SetSource,请尝试 SetDto 或者 SetSource 指定临时主键 - No properties defined + 没有定义属性 - Not implemented + 未实现 - Function expression {exp} parsing not implemented + 未实现函数表达式 {exp} 解析 - Function expression {exp} parsing not implemented, parameter {expArguments} must be constant + 未实现函数表达式 {exp} 解析,参数 {expArguments} 必须为常量 - Function expression {exp} parsing is not implemented. Use if you are working on a navigation property collection. AsSelect (). {exp3MethodName} ({exp3ArgumentsCount}) + 未实现函数表达式 {exp} 解析,如果正在操作导航属性集合,请使用 .AsSelect().{exp3MethodName}({exp3ArgumentsCount}) - Constant under MemberAccess is not implemented + 未实现 MemberAccess 下的 Constant - {name} is not implemented + 未实现 {name} - I won't support it + 不支持 - {dataType} does not support OrderByRandom sorting + {dataType} 不支持 OrderByRandom 随机排序 - {property} is not a valid navigation property + {property} 不是有效的导航属性 - {dbName} Column {memberName} not found + {dbName} 找不到列 {memberName} - Cannot find the column corresponding to {CsName} + 找不到 {CsName} 对应的列 - Attribute not found: {memberName} + 找不到属性:{memberName} - Property name {proto} not found + 找不到属性名 {proto} - Custom could not find the corresponding {{reflection information}}:{fiValueCustomArray} + Custom 找不到对应的{{ 反射信息 }}:{fiValueCustomArray} - Custom could not find the corresponding {{static method name}}:{fiValueCustomArray} + Custom 找不到对应的{{ 静态方法名 }}:{fiValueCustomArray} - The property name {atmGroupsValue} set by [Table(AsTable = xx)] does not exist + [Table(AsTable = xx)] 设置的属性名 {atmGroupsValue} 不存在 - No UseConnectionString or UseConnectionFactory specified + 未指定 UseConnectionString 或者 UseConnectionFactory - [{policyName}] ObjectPool. {GetName}() timeout {totalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081 + 【{policyName}】ObjectPool.{GetName}() timeout {totalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081 - [{policyName}] ObjectPool. GetAsync() The queue is too long. Policy. AsyncGetCapacity = {asyncGetCapacity} + 【{policyName}】ObjectPool.GetAsync() The queue is too long. Policy.AsyncGetCapacity = {asyncGetCapacity} - [OneToMany] Navigation property {trytbTypeName}.{pnvName} did not find a corresponding field in {tbrefCsName}, such as: {findtrytb}{findtrytbPkCsName}, {findtrytb}_{findtrytbPkCsName} + 【OneToMany】导航属性 {trytbTypeName}.{pnvName} 在 {tbrefCsName} 中没有找到对应的字段,如:{findtrytb}{findtrytbPkCsName}、{findtrytb}_{findtrytbPkCsName} - [OneToMany] Navigation property {trytbTypeName}.{pnvName} parsing error, {trytbCsName}.{trytbPrimarysCsName} and {tbrefCsName}.{trycolCsName} is of inconsistent type + 【OneToMany】导航属性 {trytbTypeName}.{pnvName} 解析错误,{trytbCsName}.{trytbPrimarysCsName} 和 {tbrefCsName}.{trycolCsName} 类型不一致 - , {refpropName}{findtrytbPkCsName}, {refpropName}_{findtrytbPkCsName}. Or use the [Navigate] attribute to specify the relationship mapping. + 、{refpropName}{findtrytbPkCsName}、{refpropName}_{findtrytbPkCsName}。或者使用 [Navigate] 特性指定关系映射。 - Parameter field not specified + 参数 field 未指定 - The {property} parameter is incorrect, it is not a collection property and must be IList<T>or ICollection<T> + {property} 参数错误,它不是集合属性,必须为 IList<T> 或者 ICollection<T> - The {property} parameter is incorrect, it is not a valid navigation property + {property} 参数错误,它不是有效的导航属性 - {where} parameter error, {keyval} is not a valid property name and cannot be found in entity class {reftbTypeDisplayCsharp} + {where} 参数错误,{keyval} 不是有效的属性名,在实体类 {reftbTypeDisplayCsharp} 无法找到 - {property} parameter error, format "TopicId=Id, multiple groups using comma connection" + {property} 参数错误,格式 "TopicId=Id,多组使用逗号连接" - Parsing failed {callExpMethodName} {message} + 解析失败 {callExpMethodName} {message} - [{policyName}] The ObjectPool has been disposed, see: https://github.com/dotnetcore/FreeSql/discussions/1079 + 【{policyName}】The ObjectPool has been disposed, see: https://github.com/dotnetcore/FreeSql/discussions/1079 - The {policyName} status is unavailable and cannot be used until the background checker is restored. {UnavailableExceptionMessage} + 【{policyName}】状态不可用,等待后台检查程序恢复方可使用。{UnavailableExceptionMessage} - The property {trytbVersionColumnCsName} is labeled as a row lock (optimistic lock) (IsVersion), but it must be a numeric type or byte[], and it cannot be Nullable + 属性{trytbVersionColumnCsName} 被标注为行锁(乐观锁)(IsVersion),但其必须为数字类型 或者 byte[],并且不可为 Nullable - Properrties parameter cannot be empty + properties 参数不能为空 - {property} property name not found + {property} 属性名无法找到 - Range requires that Value be comma-separated and 2-length + Range 要求 Value 应该逗号分割,并且长度为 2 - RollBack + 回滚 - Runtime error, reflection failed to get IncludeMany method + 运行时错误,反射获取 IncludeMany 方法失败 - {qoteSql} is NULL unless the attribute [Column (IsNullable = false)] + {qoteSql} is NULL,除非设置特性 [Column(IsNullable = false)] - Subtable field value'{dt}'cannot be less than'{beginTime}' + 分表字段值 "{dt}" 不能小于 "{beginTime} " - Subtable field value cannot be null + 分表字段值不能为 null - The tabular field value'{columnValue}'cannot be converted to DateTime + 分表字段值 "{columnValue}" 不能转化成 DateTime - Table field value'{dt}'does not match table name + 分表字段值 "{dt}" 未匹配到分表名 - Type T2 Error + T2 类型错误 - TableName format error, example: "log_{yyyyMMdd}" + tableName 格式错误,示例:“log_{yyyyMMdd}” - {Type}. AsType parameter error, please pass in the correct entity type + {Type}.AsType 参数错误,请传入正确的实体类型 - The {thatFullName} type cannot access the constructor + {thatFullName} 类型无法访问构造函数 - {name} type error + {name} 类型错误 - {Type}. AsType parameter does not support specifying as object + {Type}.AsType 参数不支持指定为 object - Type {typeofFullName} error, IncludeMany cannot be used + 类型 {typeofFullName} 错误,不能使用 IncludeMany - Unable to parse expression: {exp} + 无法解析表达式:{exp} - Unable to parse expression method {exp3tmpCallMethodName} + 无法解析表达式方法 {exp3tmpCallMethodName} - Please use fsql. InsertDict (dict) method inserts dictionary data + 请使用 fsql.InsertDict(dict) 方法插入字典数据 \ No newline at end of file diff --git a/FreeSql/Properties/Resources.tt b/FreeSql/Properties/Resources.tt index 104552ee5..bbd738332 100644 --- a/FreeSql/Properties/Resources.tt +++ b/FreeSql/Properties/Resources.tt @@ -21,6 +21,7 @@ using System; using System.Reflection; using System.Resources; +using System.Globalization; <# if (!model.NoDiagnostics) { @@ -62,8 +63,25 @@ namespace <#= model.Namespace #> #> <#= model.AccessModifier #> static class <#= model.Class #> { - private static readonly ResourceManager _resourceManager - = new ResourceManager("<#= model.ResourceName #>", typeof(<#= model.Class #>).Assembly); + private static readonly ResourceManager _resourceManager = new ResourceManager("<#= model.ResourceName #>", typeof(<#= model.Class #>).Assembly); + + private static CultureInfo _resourceCulture; + + /// + /// 重写当前线程的 CurrentUICulture 属性,对 + /// 使用此强类型资源类的所有资源查找执行重写。 + /// + public static CultureInfo Culture + { + get + { + return _resourceCulture; + } + set + { + _resourceCulture = value; + } + } <# foreach (var resource in model.Resources) { @@ -108,7 +126,7 @@ namespace <#= model.Namespace #> private static string GetString(string name, params string[] formatterNames) { - var value = _resourceManager.GetString(name); + var value = _resourceManager.GetString(name,_resourceCulture); for (var i = 0; i < formatterNames.Length; i++) { value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}"); @@ -161,11 +179,10 @@ namespace <#= model.Namespace #> result.Class = Path.GetFileNameWithoutExtension(resourceFile); - result.ResourceName = resourceNamespace + "." + result.Class; - + List sortedResources; - using (var reader = new ResXResourceReader(resourceFile)) + using (var reader = new ResXResourceReader(resourceFile.Replace(".resx", ".zh-Hans.resx"))) { reader.UseResXDataNodes = true; sortedResources = Enumerable.ToList(