- 增加 Aop 动态 TableName 设置;#364 #1835 #1729 #1542 #1248 #1247 #407 #387

This commit is contained in:
2881099 2024-07-11 19:00:24 +08:00
parent 36af40a868
commit 9e173aed5f
8 changed files with 117 additions and 23 deletions

View File

@ -565,7 +565,7 @@ namespace base_entity
.UseAutoSyncStructure(true) .UseAutoSyncStructure(true)
.UseNoneCommandParameter(true) .UseNoneCommandParameter(true)
//.UseNameConvert(NameConvertType.ToLower) //.UseNameConvert(NameConvertType.ToLower)
//.UseMappingPriority(MappingPriorityType.Attribute, MappingPriorityType.FluentApi, MappingPriorityType.Aop) .UseMappingPriority(MappingPriorityType.Attribute, MappingPriorityType.FluentApi, MappingPriorityType.Aop)
.UseAdoConnectionPool(true) .UseAdoConnectionPool(true)
.UseConnectionString(FreeSql.DataType.Sqlite, "data source=123.db") .UseConnectionString(FreeSql.DataType.Sqlite, "data source=123.db")
@ -619,6 +619,18 @@ namespace base_entity
BaseEntity.Initialization(fsql, () => _asyncUow.Value); BaseEntity.Initialization(fsql, () => _asyncUow.Value);
#endregion #endregion
fsql.Aop.ConfigEntity += (_, e) =>
{
e.ModifyResult.Name = Guid.NewGuid().ToString("n");
};
FreeSql.Internal.Utils.TypeHandlers.TryAdd(typeof(DateTimeOffset), new DateTimeOffsetTypeHandler());
fsql.Insert(new Account { Name = DateTime.Now.ToString(), Join = DateTimeOffset.Now }).ExecuteAffrows();
var dtslist01 = fsql.Select<Account>().As("aaa").Where(p => p.ID >= 1).AsQueryable().Select(p => new { p.Name, p.ID, p.Join }).ToList();
fsql.Select<Account>().As("aaa").Where(p => p.ID == 1).AsQueryable().Distinct().Select(p => new { p.Name, p.ID, p.Join }).Count();
var sqlc001 = fsql.Select<User1>() var sqlc001 = fsql.Select<User1>()
.GroupBy(a => a.GroupId) .GroupBy(a => a.GroupId)
@ -631,7 +643,6 @@ namespace base_entity
cou5 = g.Count(g.Value.Sort > 50 || g.Value.Username == "xx"), cou5 = g.Count(g.Value.Sort > 50 || g.Value.Username == "xx"),
}); });
fsql.Select<Account>().As("aaa").Where(p => p.ID == 1).AsQueryable().Distinct().Select(p => new { p.Name, p.ID }).Count();
var sqlt001 = fsql.Select<User1>() var sqlt001 = fsql.Select<User1>()
@ -3286,8 +3297,22 @@ public partial class ProjectItem
[Table(Name = "t_account")] [Table(Name = "t_account")]
public class Account public class Account
{ {
[Column(Name = "FID")] [Column(Name = "FID", IsIdentity = true)]
public int ID { get; set; } public int ID { get; set; }
[Column(Name = "FName")] [Column(Name = "FName")]
public string Name { get; set; } public string Name { get; set; }
[JsonProperty, Column(Name = "join", DbType = "date", MapType = typeof(string))] // 数据库类型也可以是datetime
public DateTimeOffset Join { get; set; }
}
class DateTimeOffsetTypeHandler : TypeHandler<DateTimeOffset>
{
public override object Serialize(DateTimeOffset value)
{
return value.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss");
}
public override DateTimeOffset Deserialize(object value)
{
return DateTimeOffset.TryParse((string)value, out var dts) ? dts : DateTimeOffset.MinValue;
}
} }

View File

@ -0,0 +1,35 @@
using FreeSql.DataAnnotations;
using FreeSql.Internal;
using FreeSql.Internal.Model;
using MySql.Data.MySqlClient;
using System;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.DataAnnotations
{
public class TableNameTest
{
IFreeSql fsql => g.sqlite;
[Fact]
public void ClassTableName()
{
Assert.Equal("", fsql.Select<tnt01>().ToSql().Replace("\r\n", "").Trim());
Assert.Equal("", fsql.Select<tnt01>().AsTable((t, old) => "tnt01_t").ToSql().Replace("\r\n", "").Trim());
Assert.Equal("", fsql.Insert<tnt01>().ToSql().Replace("\r\n", "").Trim());
Assert.Equal("", fsql.Insert<tnt01>().AsTable("tnt01_t").ToSql().Replace("\r\n", "").Trim());
Assert.Equal("", fsql.Delete<tnt01>().ToSql().Replace("\r\n", "").Trim());
Assert.Equal("", fsql.Delete<tnt01>().AsTable("tnt01_t").ToSql().Replace("\r\n", "").Trim());
Assert.Equal("", fsql.Update<tnt01>().SetSource(new tnt01()).ToSql().Replace("\r\n", "").Trim());
Assert.Equal("", fsql.Update<tnt01>().SetSource(new tnt01()).AsTable("tnt01_t").ToSql().Replace("\r\n", "").Trim());
Assert.Equal("", fsql.InsertOrUpdate<tnt01>().SetSource(new tnt01()).ToSql().Replace("\r\n", "").Trim());
Assert.Equal("", fsql.InsertOrUpdate<tnt01>().SetSource(new tnt01()).AsTable("tnt01_t").ToSql().Replace("\r\n", "").Trim());
}
class tnt01
{
public int id { get; set; }
public string name { get; set; }
}
}
}

View File

@ -154,10 +154,11 @@ namespace FreeSql.Internal.CommonProvider
protected string TableRuleInvoke() protected string TableRuleInvoke()
{ {
if (_tableRule == null) return _table.DbName; if (_tableRule == null && _table.AsTableImpl == null) return _commonUtils.GetEntityTableAopName(_table, true);
var newname = _tableRule(_table.DbName); var tbname = _table?.DbName ?? "";
if (newname == _table.DbName) return _table.DbName; var newname = _tableRule(tbname);
if (string.IsNullOrEmpty(newname)) return _table.DbName; if (newname == tbname) return tbname;
if (string.IsNullOrEmpty(newname)) return tbname;
if (_orm.CodeFirst.IsSyncStructureToLower) newname = newname.ToLower(); if (_orm.CodeFirst.IsSyncStructureToLower) newname = newname.ToLower();
if (_orm.CodeFirst.IsSyncStructureToUpper) newname = newname.ToUpper(); if (_orm.CodeFirst.IsSyncStructureToUpper) newname = newname.ToUpper();
if (_isAutoSyncStructure) _orm.CodeFirst.SyncStructure(_table.Type, newname); if (_isAutoSyncStructure) _orm.CodeFirst.SyncStructure(_table.Type, newname);

View File

@ -34,6 +34,7 @@ namespace FreeSql.Internal.CommonProvider
public DbConnection _connection; public DbConnection _connection;
public int _commandTimeout = 0; public int _commandTimeout = 0;
public ColumnInfo IdentityColumn { get; protected set; } public ColumnInfo IdentityColumn { get; protected set; }
public bool _isAutoSyncStructure;
} }
public abstract partial class InsertOrUpdateProvider<T1> : InsertOrUpdateProvider, IInsertOrUpdate<T1> where T1 : class public abstract partial class InsertOrUpdateProvider<T1> : InsertOrUpdateProvider, IInsertOrUpdate<T1> where T1 : class
@ -47,10 +48,11 @@ namespace FreeSql.Internal.CommonProvider
_commonUtils = commonUtils; _commonUtils = commonUtils;
_commonExpression = commonExpression; _commonExpression = commonExpression;
_table = _commonUtils.GetTableByEntity(typeof(T1)); _table = _commonUtils.GetTableByEntity(typeof(T1));
_isAutoSyncStructure = _orm.CodeFirst.IsAutoSyncStructure;
_tempPrimarys = _table?.Primarys ?? new ColumnInfo[0]; _tempPrimarys = _table?.Primarys ?? new ColumnInfo[0];
if (_table == null && typeof(T1) != typeof(Dictionary<string, object>)) if (_table == null && typeof(T1) != typeof(Dictionary<string, object>))
throw new Exception(CoreStrings.InsertOrUpdate_NotSuport_Generic_UseEntity(typeof(T1))); throw new Exception(CoreStrings.InsertOrUpdate_NotSuport_Generic_UseEntity(typeof(T1)));
if (_orm.CodeFirst.IsAutoSyncStructure && typeof(T1) != typeof(object)) _orm.CodeFirst.SyncStructure<T1>(); if (_isAutoSyncStructure && typeof(T1) != typeof(object)) _orm.CodeFirst.SyncStructure<T1>();
IdentityColumn = _table?.Primarys.Where(a => a.Attribute.IsIdentity).FirstOrDefault(); IdentityColumn = _table?.Primarys.Where(a => a.Attribute.IsIdentity).FirstOrDefault();
} }
@ -221,8 +223,8 @@ namespace FreeSql.Internal.CommonProvider
protected string TableRuleInvoke() protected string TableRuleInvoke()
{ {
if (_tableRule == null && _table.AsTableImpl == null) return _commonUtils.GetEntityTableAopName(_table, true);
var tbname = _table?.DbName ?? ""; var tbname = _table?.DbName ?? "";
if (_tableRule == null && _table.AsTableImpl == null) return tbname;
string newname = null; string newname = null;
if (_table.AsTableImpl != null) if (_table.AsTableImpl != null)
{ {
@ -231,15 +233,15 @@ namespace FreeSql.Internal.CommonProvider
else if (_tableRule == null) else if (_tableRule == null)
newname = _table.AsTableImpl.GetTableNameByColumnValue(DateTime.Now); newname = _table.AsTableImpl.GetTableNameByColumnValue(DateTime.Now);
else else
newname = _tableRule(_table.DbName); newname = _tableRule(tbname);
} }
else else
newname = _tableRule(_table.DbName); newname = _tableRule(tbname);
if (newname == tbname) return tbname; if (newname == tbname) return tbname;
if (string.IsNullOrEmpty(newname)) return tbname; if (string.IsNullOrEmpty(newname)) return tbname;
if (_orm.CodeFirst.IsSyncStructureToLower) newname = newname.ToLower(); if (_orm.CodeFirst.IsSyncStructureToLower) newname = newname.ToLower();
if (_orm.CodeFirst.IsSyncStructureToUpper) newname = newname.ToUpper(); if (_orm.CodeFirst.IsSyncStructureToUpper) newname = newname.ToUpper();
if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(_table?.Type, newname); if (_isAutoSyncStructure) _orm.CodeFirst.SyncStructure(_table?.Type, newname);
return newname; return newname;
} }
public IInsertOrUpdate<T1> AsTable(Func<string, string> tableRule) public IInsertOrUpdate<T1> AsTable(Func<string, string> tableRule)
@ -258,6 +260,7 @@ namespace FreeSql.Internal.CommonProvider
if (entityType == _table.Type) return this; if (entityType == _table.Type) return this;
var newtb = _commonUtils.GetTableByEntity(entityType); var newtb = _commonUtils.GetTableByEntity(entityType);
_table = newtb ?? throw new Exception(CoreStrings.Type_AsType_Parameter_Error("IInsertOrUpdate")); _table = newtb ?? throw new Exception(CoreStrings.Type_AsType_Parameter_Error("IInsertOrUpdate"));
if (_isAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType);
_tempPrimarys = _table.Primarys; _tempPrimarys = _table.Primarys;
if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType);
IdentityColumn = _table.Primarys.Where(a => a.Attribute.IsIdentity).FirstOrDefault(); IdentityColumn = _table.Primarys.Where(a => a.Attribute.IsIdentity).FirstOrDefault();

View File

@ -564,8 +564,8 @@ namespace FreeSql.Internal.CommonProvider
protected string TableRuleInvoke() protected string TableRuleInvoke()
{ {
if (_tableRule == null && _table.AsTableImpl == null) return _commonUtils.GetEntityTableAopName(_table, true);
var tbname = _table?.DbName ?? ""; var tbname = _table?.DbName ?? "";
if (_tableRule == null && _table.AsTableImpl == null) return tbname;
string newname = null; string newname = null;
if (_table.AsTableImpl != null) if (_table.AsTableImpl != null)
{ {
@ -574,10 +574,10 @@ namespace FreeSql.Internal.CommonProvider
else if (_tableRule == null) else if (_tableRule == null)
newname = _table.AsTableImpl.GetTableNameByColumnValue(DateTime.Now); newname = _table.AsTableImpl.GetTableNameByColumnValue(DateTime.Now);
else else
newname = _tableRule(_table.DbName); newname = _tableRule(tbname);
} }
else else
newname = _tableRule(_table.DbName); newname = _tableRule(tbname);
if (newname == tbname) return tbname; if (newname == tbname) return tbname;
if (string.IsNullOrEmpty(newname)) return tbname; if (string.IsNullOrEmpty(newname)) return tbname;
if (_orm.CodeFirst.IsSyncStructureToLower) newname = newname.ToLower(); if (_orm.CodeFirst.IsSyncStructureToLower) newname = newname.ToLower();

View File

@ -877,7 +877,7 @@ namespace FreeSql.Internal.CommonProvider
DateTime? DateTimeAsTableImplStart = null, DateTimeAsTableImplEnd = null; DateTime? DateTimeAsTableImplStart = null, DateTimeAsTableImplEnd = null;
string[] LocalGetTableNames(SelectTableInfo tb) string[] LocalGetTableNames(SelectTableInfo tb)
{ {
var trname = trs[0](tb.Table.Type, tb.Table.AsTableImpl != null ? null : tb.Table.DbName); var trname = trs[0](tb.Table.Type, tb.Table.AsTableImpl != null ? null : _commonUtils.GetEntityTableAopName(tb.Table, false));
if (tb.Table.AsTableImpl != null && string.IsNullOrWhiteSpace(trname) == true) if (tb.Table.AsTableImpl != null && string.IsNullOrWhiteSpace(trname) == true)
{ {
var aret = tb.Table.AsTableImpl.GetTableNamesBySqlWhere(_where.Length == 0 ? null : _where.ToString(), _params, tb, _commonUtils); var aret = tb.Table.AsTableImpl.GetTableNamesBySqlWhere(_where.Length == 0 ? null : _where.ToString(), _params, tb, _commonUtils);

View File

@ -897,7 +897,8 @@ namespace FreeSql.Internal.CommonProvider
protected string TableRuleInvoke() protected string TableRuleInvoke()
{ {
if (_tableRule == null && _table.AsTableImpl == null) return _table.DbName; if (_tableRule == null && _table.AsTableImpl == null) return _commonUtils.GetEntityTableAopName(_table, true);
var tbname = _table?.DbName ?? "";
string newname = null; string newname = null;
if (_table.AsTableImpl != null) if (_table.AsTableImpl != null)
{ {
@ -906,12 +907,12 @@ namespace FreeSql.Internal.CommonProvider
else if (_tableRule == null) else if (_tableRule == null)
newname = _table.AsTableImpl.GetTableNameByColumnValue(DateTime.Now); newname = _table.AsTableImpl.GetTableNameByColumnValue(DateTime.Now);
else else
newname = _tableRule(_table.DbName); newname = _tableRule(tbname);
} }
else else
newname = _tableRule(_table.DbName); newname = _tableRule(tbname);
if (newname == _table.DbName) return _table.DbName; if (newname == tbname) return tbname;
if (string.IsNullOrEmpty(newname)) return _table.DbName; if (string.IsNullOrEmpty(newname)) return tbname;
if (_orm.CodeFirst.IsSyncStructureToLower) newname = newname.ToLower(); if (_orm.CodeFirst.IsSyncStructureToLower) newname = newname.ToLower();
if (_orm.CodeFirst.IsSyncStructureToUpper) newname = newname.ToUpper(); if (_orm.CodeFirst.IsSyncStructureToUpper) newname = newname.ToUpper();
if (_isAutoSyncStructure) _orm.CodeFirst.SyncStructure(_table.Type, newname); if (_isAutoSyncStructure) _orm.CodeFirst.SyncStructure(_table.Type, newname);

View File

@ -134,6 +134,35 @@ namespace FreeSql.Internal
return dicConfigEntity.TryGetValue(type, out var trytb) ? trytb : null; return dicConfigEntity.TryGetValue(type, out var trytb) ? trytb : null;
} }
public string GetEntityTableAopName(TableInfo table, bool flag1)
{
if (table != null && _orm.Aop.ConfigEntityHandler != null && _mappingPriorityTypes.LastOrDefault() == MappingPriorityType.Aop)
{
var newname = table.DbName;
var aope = new Aop.ConfigEntityEventArgs(table.Type)
{
ModifyResult = new TableAttribute
{
Name = table.DbName,
_DisableSyncStructure = table.DisableSyncStructure,
}
};
_orm.Aop.ConfigEntityHandler(_orm, aope);
var tryattr = aope.ModifyResult;
if (!string.IsNullOrEmpty(tryattr.Name)) newname = tryattr.Name;
if (newname == table.DbName) return table.DbName;
if (string.IsNullOrEmpty(newname)) return table.DbName;
if (flag1)
{
if (_orm.CodeFirst.IsSyncStructureToLower) newname = newname.ToLower();
if (_orm.CodeFirst.IsSyncStructureToUpper) newname = newname.ToUpper();
if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(table.Type, newname);
}
return newname;
}
return table?.DbName;
}
public MappingPriorityType[] _mappingPriorityTypes = new[] { MappingPriorityType.Aop, MappingPriorityType.FluentApi, MappingPriorityType.Attribute }; public MappingPriorityType[] _mappingPriorityTypes = new[] { MappingPriorityType.Aop, MappingPriorityType.FluentApi, MappingPriorityType.Attribute };
ConcurrentDictionary<Type, Dictionary<string, IndexAttribute>> dicAopConfigEntityIndex = new ConcurrentDictionary<Type, Dictionary<string, IndexAttribute>>(); ConcurrentDictionary<Type, Dictionary<string, IndexAttribute>> dicAopConfigEntityIndex = new ConcurrentDictionary<Type, Dictionary<string, IndexAttribute>>();
public TableAttribute GetEntityTableAttribute(Type type) public TableAttribute GetEntityTableAttribute(Type type)
@ -158,7 +187,7 @@ namespace FreeSql.Internal
}; };
_orm.Aop.ConfigEntityHandler(_orm, aope); _orm.Aop.ConfigEntityHandler(_orm, aope);
var tryattr = aope.ModifyResult; var tryattr = aope.ModifyResult;
if (!string.IsNullOrEmpty(tryattr.Name) && tryattr.Name != type.Name) attr.Name = tryattr.Name; if (!string.IsNullOrEmpty(tryattr.Name)) attr.Name = tryattr.Name;
if (!string.IsNullOrEmpty(tryattr.OldName)) attr.OldName = tryattr.OldName; if (!string.IsNullOrEmpty(tryattr.OldName)) attr.OldName = tryattr.OldName;
if (tryattr._DisableSyncStructure != null) attr._DisableSyncStructure = tryattr.DisableSyncStructure; if (tryattr._DisableSyncStructure != null) attr._DisableSyncStructure = tryattr.DisableSyncStructure;
if (!string.IsNullOrEmpty(tryattr.AsTable)) attr.AsTable = tryattr.AsTable; if (!string.IsNullOrEmpty(tryattr.AsTable)) attr.AsTable = tryattr.AsTable;
@ -239,7 +268,7 @@ namespace FreeSql.Internal
}; };
_orm.Aop.ConfigEntityPropertyHandler(_orm, aope); _orm.Aop.ConfigEntityPropertyHandler(_orm, aope);
var tryattr = aope.ModifyResult; var tryattr = aope.ModifyResult;
if (!string.IsNullOrEmpty(tryattr.Name) && tryattr.Name != proto.Name) attr.Name = tryattr.Name; if (!string.IsNullOrEmpty(tryattr.Name)) attr.Name = tryattr.Name;
if (!string.IsNullOrEmpty(tryattr.OldName)) attr.OldName = tryattr.OldName; if (!string.IsNullOrEmpty(tryattr.OldName)) attr.OldName = tryattr.OldName;
if (!string.IsNullOrEmpty(tryattr.DbType)) attr.DbType = tryattr.DbType; if (!string.IsNullOrEmpty(tryattr.DbType)) attr.DbType = tryattr.DbType;
if (tryattr._IsPrimary != null) attr._IsPrimary = tryattr.IsPrimary; if (tryattr._IsPrimary != null) attr._IsPrimary = tryattr.IsPrimary;