Skip to content

Commit

Permalink
- 增加 Aop 动态 TableName 设置;#364 #1835 #1729 #1542 #1248 #1247 #407 #387
Browse files Browse the repository at this point in the history
  • Loading branch information
2881099 committed Jul 11, 2024
1 parent 36af40a commit 9e173ae
Show file tree
Hide file tree
Showing 8 changed files with 117 additions and 23 deletions.
31 changes: 28 additions & 3 deletions Examples/base_entity/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -565,7 +565,7 @@ static void Main(string[] args)
.UseAutoSyncStructure(true)
.UseNoneCommandParameter(true)
//.UseNameConvert(NameConvertType.ToLower)
//.UseMappingPriority(MappingPriorityType.Attribute, MappingPriorityType.FluentApi, MappingPriorityType.Aop)
.UseMappingPriority(MappingPriorityType.Attribute, MappingPriorityType.FluentApi, MappingPriorityType.Aop)
.UseAdoConnectionPool(true)

.UseConnectionString(FreeSql.DataType.Sqlite, "data source=123.db")
Expand Down Expand Up @@ -619,6 +619,18 @@ static void Main(string[] args)
BaseEntity.Initialization(fsql, () => _asyncUow.Value);
#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>()
.GroupBy(a => a.GroupId)
Expand All @@ -631,7 +643,6 @@ static void Main(string[] args)
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>()
Expand Down Expand Up @@ -3286,8 +3297,22 @@ public partial class ProjectItem
[Table(Name = "t_account")]
public class Account
{
[Column(Name = "FID")]
[Column(Name = "FID", IsIdentity = true)]
public int ID { get; set; }
[Column(Name = "FName")]
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;
}
}
35 changes: 35 additions & 0 deletions FreeSql.Tests/FreeSql.Tests/DataAnnotations/TableNameTest.cs
Original file line number Diff line number Diff line change
@@ -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; }
}
}
}
9 changes: 5 additions & 4 deletions FreeSql/Internal/CommonProvider/DeleteProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,11 @@ public IDelete<T1> DisableGlobalFilter(params string[] name)

protected string TableRuleInvoke()
{
if (_tableRule == null) return _table.DbName;
var newname = _tableRule(_table.DbName);
if (newname == _table.DbName) return _table.DbName;
if (string.IsNullOrEmpty(newname)) return _table.DbName;
if (_tableRule == null && _table.AsTableImpl == null) return _commonUtils.GetEntityTableAopName(_table, true);
var tbname = _table?.DbName ?? "";
var newname = _tableRule(tbname);
if (newname == tbname) return tbname;
if (string.IsNullOrEmpty(newname)) return tbname;
if (_orm.CodeFirst.IsSyncStructureToLower) newname = newname.ToLower();
if (_orm.CodeFirst.IsSyncStructureToUpper) newname = newname.ToUpper();
if (_isAutoSyncStructure) _orm.CodeFirst.SyncStructure(_table.Type, newname);
Expand Down
13 changes: 8 additions & 5 deletions FreeSql/Internal/CommonProvider/InsertOrUpdateProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public abstract partial class InsertOrUpdateProvider
public DbConnection _connection;
public int _commandTimeout = 0;
public ColumnInfo IdentityColumn { get; protected set; }
public bool _isAutoSyncStructure;
}

public abstract partial class InsertOrUpdateProvider<T1> : InsertOrUpdateProvider, IInsertOrUpdate<T1> where T1 : class
Expand All @@ -47,10 +48,11 @@ public InsertOrUpdateProvider(IFreeSql orm, CommonUtils commonUtils, CommonExpre
_commonUtils = commonUtils;
_commonExpression = commonExpression;
_table = _commonUtils.GetTableByEntity(typeof(T1));
_isAutoSyncStructure = _orm.CodeFirst.IsAutoSyncStructure;
_tempPrimarys = _table?.Primarys ?? new ColumnInfo[0];
if (_table == null && typeof(T1) != typeof(Dictionary<string, object>))
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();
}

Expand Down Expand Up @@ -221,8 +223,8 @@ public virtual IInsertOrUpdate<T1> BatchOptions(int valuesLimit, bool autoTransa

protected string TableRuleInvoke()
{
if (_tableRule == null && _table.AsTableImpl == null) return _commonUtils.GetEntityTableAopName(_table, true);
var tbname = _table?.DbName ?? "";
if (_tableRule == null && _table.AsTableImpl == null) return tbname;
string newname = null;
if (_table.AsTableImpl != null)
{
Expand All @@ -231,15 +233,15 @@ protected string TableRuleInvoke()
else if (_tableRule == null)
newname = _table.AsTableImpl.GetTableNameByColumnValue(DateTime.Now);
else
newname = _tableRule(_table.DbName);
newname = _tableRule(tbname);
}
else
newname = _tableRule(_table.DbName);
newname = _tableRule(tbname);
if (newname == tbname) return tbname;
if (string.IsNullOrEmpty(newname)) return tbname;
if (_orm.CodeFirst.IsSyncStructureToLower) newname = newname.ToLower();
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;
}
public IInsertOrUpdate<T1> AsTable(Func<string, string> tableRule)
Expand All @@ -258,6 +260,7 @@ public IInsertOrUpdate<T1> AsType(Type entityType)
if (entityType == _table.Type) return this;
var newtb = _commonUtils.GetTableByEntity(entityType);
_table = newtb ?? throw new Exception(CoreStrings.Type_AsType_Parameter_Error("IInsertOrUpdate"));
if (_isAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType);
_tempPrimarys = _table.Primarys;
if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType);
IdentityColumn = _table.Primarys.Where(a => a.Attribute.IsIdentity).FirstOrDefault();
Expand Down
6 changes: 3 additions & 3 deletions FreeSql/Internal/CommonProvider/InsertProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -564,8 +564,8 @@ public IInsert<T1> IgnoreInsertValueSql(string[] columns)

protected string TableRuleInvoke()
{
if (_tableRule == null && _table.AsTableImpl == null) return _commonUtils.GetEntityTableAopName(_table, true);
var tbname = _table?.DbName ?? "";
if (_tableRule == null && _table.AsTableImpl == null) return tbname;
string newname = null;
if (_table.AsTableImpl != null)
{
Expand All @@ -574,10 +574,10 @@ protected string TableRuleInvoke()
else if (_tableRule == null)
newname = _table.AsTableImpl.GetTableNameByColumnValue(DateTime.Now);
else
newname = _tableRule(_table.DbName);
newname = _tableRule(tbname);
}
else
newname = _tableRule(_table.DbName);
newname = _tableRule(tbname);
if (newname == tbname) return tbname;
if (string.IsNullOrEmpty(newname)) return tbname;
if (_orm.CodeFirst.IsSyncStructureToLower) newname = newname.ToLower();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -877,7 +877,7 @@ protected List<Dictionary<Type, string>> GetTableRuleUnions()
DateTime? DateTimeAsTableImplStart = null, DateTimeAsTableImplEnd = null;
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)
{
var aret = tb.Table.AsTableImpl.GetTableNamesBySqlWhere(_where.Length == 0 ? null : _where.ToString(), _params, tb, _commonUtils);
Expand Down
11 changes: 6 additions & 5 deletions FreeSql/Internal/CommonProvider/UpdateProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -897,7 +897,8 @@ protected virtual void ToSqlCaseWhenEnd(StringBuilder sb, ColumnInfo col) { }

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;
if (_table.AsTableImpl != null)
{
Expand All @@ -906,12 +907,12 @@ protected string TableRuleInvoke()
else if (_tableRule == null)
newname = _table.AsTableImpl.GetTableNameByColumnValue(DateTime.Now);
else
newname = _tableRule(_table.DbName);
newname = _tableRule(tbname);
}
else
newname = _tableRule(_table.DbName);
if (newname == _table.DbName) return _table.DbName;
if (string.IsNullOrEmpty(newname)) return _table.DbName;
newname = _tableRule(tbname);
if (newname == tbname) return tbname;
if (string.IsNullOrEmpty(newname)) return tbname;
if (_orm.CodeFirst.IsSyncStructureToLower) newname = newname.ToLower();
if (_orm.CodeFirst.IsSyncStructureToUpper) newname = newname.ToUpper();
if (_isAutoSyncStructure) _orm.CodeFirst.SyncStructure(_table.Type, newname);
Expand Down
33 changes: 31 additions & 2 deletions FreeSql/Internal/CommonUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,35 @@ public TableAttribute GetConfigEntity(Type type)
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 };
ConcurrentDictionary<Type, Dictionary<string, IndexAttribute>> dicAopConfigEntityIndex = new ConcurrentDictionary<Type, Dictionary<string, IndexAttribute>>();
public TableAttribute GetEntityTableAttribute(Type type)
Expand All @@ -158,7 +187,7 @@ public TableAttribute GetEntityTableAttribute(Type type)
};
_orm.Aop.ConfigEntityHandler(_orm, aope);
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 (tryattr._DisableSyncStructure != null) attr._DisableSyncStructure = tryattr.DisableSyncStructure;
if (!string.IsNullOrEmpty(tryattr.AsTable)) attr.AsTable = tryattr.AsTable;
Expand Down Expand Up @@ -239,7 +268,7 @@ public ColumnAttribute GetEntityColumnAttribute(Type type, PropertyInfo proto)
};
_orm.Aop.ConfigEntityPropertyHandler(_orm, aope);
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.DbType)) attr.DbType = tryattr.DbType;
if (tryattr._IsPrimary != null) attr._IsPrimary = tryattr.IsPrimary;
Expand Down

0 comments on commit 9e173ae

Please sign in to comment.