- 增加 EfCoreFluentApi 扩展包,接近 efcore fluentApi 的使用习惯;#4

- 增加 ColumnAttribute 属性 InsertValueSql,插入数据的时候指定用 sql 值;
This commit is contained in:
28810 2019-12-29 15:30:43 +08:00
parent 20ffad0ba3
commit 8cb7ef2130
14 changed files with 721 additions and 163 deletions

View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using FreeSql.DataAnnotations;
namespace FreeSql.Extensions.EfCoreFluentApi
{
public class EfCoreColumnFluent
{
ColumnFluent _cf;
internal EfCoreColumnFluent(ColumnFluent tf)
{
_cf = tf;
}
public ColumnFluent Help() => _cf;
public EfCoreColumnFluent HasColumnName(string name)
{
_cf.Name(name);
return this;
}
public EfCoreColumnFluent HashColumnType(string dbtype)
{
_cf.DbType(dbtype);
return this;
}
public EfCoreColumnFluent IsRequired()
{
_cf.IsNullable(false);
return this;
}
public EfCoreColumnFluent HasMaxLength(int length)
{
_cf.StringLength(length);
return this;
}
public EfCoreColumnFluent HasDefaultValueSql(string sqlValue)
{
_cf.InsertValueSql(sqlValue);
return this;
}
public EfCoreColumnFluent IsRowVersion()
{
_cf.IsVersion(true);
return this;
}
//public EfCoreColumnFluent HasConversion(Func<object, string> stringify, Func<string, object> parse)
//{
// return this;
//}
}
}

View File

@ -0,0 +1,312 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using FreeSql.DataAnnotations;
namespace FreeSql.Extensions.EfCoreFluentApi
{
public class EfCoreTableFluent<T>
{
TableFluent<T> _tf;
internal EfCoreTableFluent(TableFluent<T> tf)
{
_tf = tf;
}
public EfCoreTableFluent<T> ToTable(string name)
{
_tf.Name(name);
return this;
}
public EfCoreTableFluent<T> ToView(string name)
{
_tf.DisableSyncStructure(true);
_tf.Name(name);
return this;
}
public EfCoreColumnFluent Property<TProperty>(Expression<Func<T, TProperty>> property) => new EfCoreColumnFluent(_tf.Property(property));
public EfCoreColumnFluent Property(string property) => new EfCoreColumnFluent(_tf.Property(property));
public TableFluent<T> Help() => _tf;
#region HasKey
public EfCoreTableFluent<T> HasKey(Expression<Func<T, object>> key)
{
if (key?.Body == null) return this;
var exp = key.Body;
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
_tf.Property((exp as MemberExpression).Member.Name).IsPrimary(true);
break;
case ExpressionType.New:
foreach (var member in (exp as NewExpression).Members)
_tf.Property(member.Name).IsPrimary(true);
break;
}
return this;
}
#endregion
#region HasIndex
public HasIndexFluent HasIndex(Expression<Func<T, object>> index)
{
if (index?.Body == null) throw new ArgumentException("参数错误 index 不能为 null");
var exp = index.Body;
var indexName = $"idx_{Guid.NewGuid().ToString("N").Substring(0, 8)}";
var columns = new List<string>();
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
columns.Add((exp as MemberExpression).Member.Name);
break;
case ExpressionType.New:
foreach (var member in (exp as NewExpression).Members)
columns.Add(member.Name);
break;
}
_tf.Index(indexName, string.Join(", ", columns), false);
return new HasIndexFluent(_tf, indexName, columns);
}
public class HasIndexFluent
{
TableFluent<T> _modelBuilder;
string _indexName;
List<string> _columns;
bool _isUnique;
internal HasIndexFluent(TableFluent<T> modelBuilder, string indexName, List<string> columns)
{
_modelBuilder = modelBuilder;
_indexName = indexName;
_columns = columns;
}
public HasIndexFluent IsUnique()
{
_isUnique = true;
_modelBuilder.Index(_indexName, string.Join(", ", _columns), _isUnique);
return this;
}
public HasIndexFluent HasName(string name)
{
_modelBuilder.IndexRemove(_indexName);
_indexName = name;
_modelBuilder.Index(_indexName, string.Join(", ", _columns), _isUnique);
return this;
}
}
#endregion
#region HasOne
public HasOneFluent<T2> HasOne<T2>(Expression<Func<T, T2>> one)
{
if (one?.Body == null) throw new ArgumentException("参数错误 one 不能为 null");
var exp = one.Body;
var oneProperty = "";
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
oneProperty = (exp as MemberExpression).Member.Name;
break;
}
if (string.IsNullOrEmpty(oneProperty)) throw new ArgumentException("参数错误 one");
return new HasOneFluent<T2>(_tf, oneProperty);
}
public class HasOneFluent<T2>
{
TableFluent<T> _tf;
string _selfProperty;
string _selfBind;
string _withManyProperty;
string _withOneProperty;
string _withOneBind;
internal HasOneFluent(TableFluent<T> modelBuilder, string oneProperty)
{
_tf = modelBuilder;
_selfProperty = oneProperty;
}
public HasOneFluent<T2> WithMany<TMany>(Expression<Func<T2, TMany>> many)
{
if (many?.Body == null) throw new ArgumentException("参数错误 many 不能为 null");
var exp = many.Body;
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
_withManyProperty = (exp as MemberExpression).Member.Name;
break;
}
if (string.IsNullOrEmpty(_withManyProperty)) throw new ArgumentException("参数错误 many");
if (string.IsNullOrEmpty(_selfBind) == false)
_tf.ConfigEntity<T2>(eb2 => eb2.Navigate(_withManyProperty, _selfBind));
return this;
}
public HasOneFluent<T2> WithOne(Expression<Func<T2, T>> one, Expression<Func<T2, object>> foreignKey)
{
if (one?.Body == null) throw new ArgumentException("参数错误 one 不能为 null");
var exp = one.Body;
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
_withOneProperty = (exp as MemberExpression).Member.Name;
break;
}
if (string.IsNullOrEmpty(_withOneProperty)) throw new ArgumentException("参数错误 one");
if (foreignKey?.Body == null) throw new ArgumentException("参数错误 foreignKey 不能为 null");
exp = foreignKey.Body;
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
_withOneBind = (exp as MemberExpression).Member.Name;
_withOneBind = _withOneBind.TrimStart(',', ' ');
break;
case ExpressionType.New:
_withOneBind = "";
foreach (var member in (exp as NewExpression).Members)
_withOneBind += ", " + member.Name;
_withOneBind = _withOneBind.TrimStart(',', ' ');
break;
}
if (string.IsNullOrEmpty(_withOneBind)) throw new ArgumentException("参数错误 foreignKey");
if (string.IsNullOrEmpty(_selfBind) == false)
_tf.ConfigEntity<T2>(eb2 => eb2.Navigate(_withOneProperty, _withOneBind));
return this;
}
public HasOneFluent<T2> HasForeignKey(Expression<Func<T, object>> foreignKey)
{
if (foreignKey?.Body == null) throw new ArgumentException("参数错误 foreignKey 不能为 null");
var exp = foreignKey.Body;
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
_selfBind = (exp as MemberExpression).Member.Name;
_selfBind = _selfBind.TrimStart(',', ' ');
break;
case ExpressionType.New:
_selfBind = "";
foreach (var member in (exp as NewExpression).Members)
_selfBind += ", " + member.Name;
_selfBind = _selfBind.TrimStart(',', ' ');
break;
}
if (string.IsNullOrEmpty(_selfBind)) throw new ArgumentException("参数错误 foreignKey");
_tf.Navigate(_selfProperty, _selfBind);
if (string.IsNullOrEmpty(_withManyProperty) == false)
_tf.ConfigEntity<T2>(eb2 => eb2.Navigate(_withManyProperty, _selfBind));
if (string.IsNullOrEmpty(_withOneProperty) == false && string.IsNullOrEmpty(_withOneBind) == false)
_tf.ConfigEntity<T2>(eb2 => eb2.Navigate(_withOneProperty, _withOneBind));
return this;
}
}
#endregion
#region HasMany
public HasManyFluent<T2> HasMany<T2>(Expression<Func<T, IEnumerable<T2>>> many)
{
if (many?.Body == null) throw new ArgumentException("参数错误 many 不能为 null");
var exp = many.Body;
var manyProperty = "";
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
manyProperty = (exp as MemberExpression).Member.Name;
break;
}
if (string.IsNullOrEmpty(manyProperty)) throw new ArgumentException("参数错误 many");
return new HasManyFluent<T2>(_tf, manyProperty);
}
public class HasManyFluent<T2>
{
TableFluent<T> _tf;
string _selfProperty;
string _selfBind;
string _withOneProperty;
string _withManyProperty;
internal HasManyFluent(TableFluent<T> modelBuilder, string manyProperty)
{
_tf = modelBuilder;
_selfProperty = manyProperty;
}
public void WithMany(Expression<Func<T2, IEnumerable<T>>> many, Type middleType)
{
if (many?.Body == null) throw new ArgumentException("参数错误 many 不能为 null");
var exp = many.Body;
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
_withManyProperty = (exp as MemberExpression).Member.Name;
break;
}
if (string.IsNullOrEmpty(_withManyProperty)) throw new ArgumentException("参数错误 many");
_tf.Navigate(_selfProperty, null, middleType);
_tf.ConfigEntity<T2>(eb2 => eb2.Navigate(_withManyProperty, null, middleType));
}
public HasManyFluent<T2> WithOne(Expression<Func<T2, T>> one)
{
if (one?.Body == null) throw new ArgumentException("参数错误 one 不能为 null");
var exp = one.Body;
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
_withOneProperty = (exp as MemberExpression).Member.Name;
break;
}
if (string.IsNullOrEmpty(_withOneProperty)) throw new ArgumentException("参数错误 one");
if (string.IsNullOrEmpty(_selfBind) == false)
_tf.ConfigEntity<T2>(eb2 => eb2.Navigate(_withOneProperty, _selfBind));
return this;
}
public HasManyFluent<T2> HasForeignKey(Expression<Func<T, object>> foreignKey)
{
if (foreignKey?.Body == null) throw new ArgumentException("参数错误 foreignKey 不能为 null");
var exp = foreignKey.Body;
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
_selfBind = (exp as MemberExpression).Member.Name;
_selfBind = _selfBind.TrimStart(',', ' ');
break;
case ExpressionType.New:
_selfBind = "";
foreach (var member in (exp as NewExpression).Members)
_selfBind += ", " + member.Name;
_selfBind = _selfBind.TrimStart(',', ' ');
break;
}
if (string.IsNullOrEmpty(_selfBind)) throw new ArgumentException("参数错误 foreignKey");
_tf.Navigate(_selfProperty, _selfBind);
if (string.IsNullOrEmpty(_withOneProperty) == false)
_tf.ConfigEntity<T2>(eb2 => eb2.Navigate(_withOneProperty, _selfBind));
return this;
}
}
#endregion
public EfCoreTableFluent<T> Ignore<TProperty>(Expression<Func<T, TProperty>> property)
{
_tf.Property(property).IsIgnore(true);
return this;
}
//public EfCoreTableFluent<T> HasData(T data) => HasData(new[] { data });
//public EfCoreTableFluent<T> HasData(IEnumerable<T> data)
//{
// return this;
//}
}
}

View File

@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0</TargetFrameworks>
<Version>1.0.0</Version>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Authors>YeXiangQin</Authors>
<Description>FreeSql 扩展包实现,使用 FluentApi 方式配置实体模型,使用习惯接近 EFCore方便过渡.</Description>
<PackageProjectUrl>https://github.com/2881099/FreeSql</PackageProjectUrl>
<RepositoryUrl>https://github.com/2881099/FreeSql</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageTags>FreeSql;ORM;FluentApi</PackageTags>
<PackageId>$(AssemblyName)</PackageId>
<PackageIcon>logo.png</PackageIcon>
<Title>$(AssemblyName)</Title>
<IsPackable>true</IsPackable>
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
</PropertyGroup>
<ItemGroup>
<None Include="../../logo.png" Pack="true" PackagePath="\" />
</ItemGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|netstandard2.0|AnyCPU'">
<DocumentationFile>FreeSql.Extensions.EfCoreFluentApi.xml</DocumentationFile>
<WarningLevel>3</WarningLevel>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\FreeSql\FreeSql.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using FreeSql.DataAnnotations;
namespace FreeSql.Extensions.EfCoreFluentApi
{
public static class ICodeFirstExtensions
{
static void Test()
{
ICodeFirst cf = null;
cf.Entity<TestInfo>(eb =>
{
eb.Property(b => b.Name).HashColumnType("varchar(50)");
eb.Property(b => b.FullName).HashColumnType("varchar(60)");
eb.HasKey(a => a.Id).HasKey(a => new { a.Id, a.Name });
eb.HasIndex(a => a.Name).IsUnique().HasName("idx_xxx11");
});
}
class TestInfo
{
public int Id { get; set; }
public string Name { get; set; }
public string FullName { get; set; }
public int DefaultValue { get; set; }
}
public static ICodeFirst Entity<T>(this ICodeFirst codeFirst, Action<EfCoreTableFluent<T>> modelBuilder)
{
codeFirst.ConfigEntity<T>(tf => modelBuilder(new EfCoreTableFluent<T>(tf)));
return codeFirst;
}
}
}

View File

@ -110,6 +110,13 @@
清空状态数据 清空状态数据
</summary> </summary>
</member> </member>
<member name="M:FreeSql.DbSet`1.RemoveAsync(System.Linq.Expressions.Expression{System.Func{`0,System.Boolean}})">
<summary>
根据 lambda 条件删除数据
</summary>
<param name="predicate"></param>
<returns></returns>
</member>
<member name="M:FreeSql.DbSet`1.Add(`0)"> <member name="M:FreeSql.DbSet`1.Add(`0)">
<summary> <summary>
添加 添加

View File

@ -12,6 +12,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="IdleBus" Version="1.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
<PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit" Version="2.4.1" />

View File

@ -51,6 +51,39 @@ namespace FreeSql.Tests
//var getTestByte = g.sqlserver.Select<TestByte>(testByte).First(); //var getTestByte = g.sqlserver.Select<TestByte>(testByte).First();
//File.WriteAllBytes(@"C:\Users\28810\Desktop\71500003-0ad69400-289e-11ea-85cb-36a54f52ebc0_write.png", getTestByte.pic); //File.WriteAllBytes(@"C:\Users\28810\Desktop\71500003-0ad69400-289e-11ea-85cb-36a54f52ebc0_write.png", getTestByte.pic);
var ib = new IdleBus<IFreeSql>(TimeSpan.FromMinutes(10), 2);
ib.Notice += (_, e2) => Trace.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] 线程{Thread.CurrentThread.ManagedThreadId}{e2.Log}");
ib.Register("db1", () => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=3")
.UseAutoSyncStructure(true)
.UseMonitorCommand(cmd => Trace.WriteLine("\r\n线程" + Thread.CurrentThread.ManagedThreadId + ": " + cmd.CommandText))
.UseLazyLoading(true)
.Build());
ib.Register("db2", () => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=3")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
.UseSyncStructureToUpper(true)
.UseMonitorCommand(cmd => Trace.WriteLine("\r\n线程" + Thread.CurrentThread.ManagedThreadId + ": " + cmd.CommandText))
.Build());
ib.Register("db3", () => new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=3")
.UseAutoSyncStructure(true)
.UseLazyLoading(true)
.UseMonitorCommand(cmd => Trace.WriteLine("\r\n线程" + Thread.CurrentThread.ManagedThreadId + ": " + cmd.CommandText))
.Build());
//...注入很多个
var fsql = ib.Get("db1"); //使用的时候用 Get 方法,不要存其引用关系
fsql.Select<ut3_t1>().Limit(10).ToList();
fsql = ib.Get("db2");
fsql.Select<ut3_t1>().Limit(10).ToList();
fsql = ib.Get("db3");
fsql.Select<ut3_t1>().Limit(10).ToList();
} }
class TestByte class TestByte

View File

@ -72,6 +72,8 @@ Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "FreeSql.Tests.VB", "FreeSql
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FreeSql.Provider.MsAccess", "Providers\FreeSql.Provider.MsAccess\FreeSql.Provider.MsAccess.csproj", "{B397A761-F646-41CF-A160-AB6C05DAF2FB}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FreeSql.Provider.MsAccess", "Providers\FreeSql.Provider.MsAccess\FreeSql.Provider.MsAccess.csproj", "{B397A761-F646-41CF-A160-AB6C05DAF2FB}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FreeSql.Extensions.EfCoreFluentApi", "Extensions\FreeSql.Extensions.EfCoreFluentApi\FreeSql.Extensions.EfCoreFluentApi.csproj", "{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -430,6 +432,18 @@ Global
{B397A761-F646-41CF-A160-AB6C05DAF2FB}.Release|x64.Build.0 = Release|Any CPU {B397A761-F646-41CF-A160-AB6C05DAF2FB}.Release|x64.Build.0 = Release|Any CPU
{B397A761-F646-41CF-A160-AB6C05DAF2FB}.Release|x86.ActiveCfg = Release|Any CPU {B397A761-F646-41CF-A160-AB6C05DAF2FB}.Release|x86.ActiveCfg = Release|Any CPU
{B397A761-F646-41CF-A160-AB6C05DAF2FB}.Release|x86.Build.0 = Release|Any CPU {B397A761-F646-41CF-A160-AB6C05DAF2FB}.Release|x86.Build.0 = Release|Any CPU
{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F}.Debug|x64.ActiveCfg = Debug|Any CPU
{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F}.Debug|x64.Build.0 = Debug|Any CPU
{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F}.Debug|x86.ActiveCfg = Debug|Any CPU
{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F}.Debug|x86.Build.0 = Debug|Any CPU
{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F}.Release|Any CPU.Build.0 = Release|Any CPU
{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F}.Release|x64.ActiveCfg = Release|Any CPU
{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F}.Release|x64.Build.0 = Release|Any CPU
{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F}.Release|x86.ActiveCfg = Release|Any CPU
{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
@ -455,6 +469,7 @@ Global
{1674BCE3-EEB4-4003-A2A7-06F51EFAEA23} = {94C8A78D-AA15-47B2-A348-530CD86BFC1B} {1674BCE3-EEB4-4003-A2A7-06F51EFAEA23} = {94C8A78D-AA15-47B2-A348-530CD86BFC1B}
{6A3A4470-7DF7-411B-AAD7-755D7A9DB5A4} = {4A92E8A6-9A6D-41A1-9CDA-DE10899648AA} {6A3A4470-7DF7-411B-AAD7-755D7A9DB5A4} = {4A92E8A6-9A6D-41A1-9CDA-DE10899648AA}
{B397A761-F646-41CF-A160-AB6C05DAF2FB} = {2A381C57-2697-427B-9F10-55DA11FD02E4} {B397A761-F646-41CF-A160-AB6C05DAF2FB} = {2A381C57-2697-427B-9F10-55DA11FD02E4}
{773D5B63-DE6E-46DB-AF16-6FB1C1352B3F} = {4A92E8A6-9A6D-41A1-9CDA-DE10899648AA}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {089687FD-5D25-40AB-BA8A-A10D1E137F98} SolutionGuid = {089687FD-5D25-40AB-BA8A-A10D1E137F98}

View File

@ -97,5 +97,11 @@ namespace FreeSql.DataAnnotations
/// Sqlite -> text<para></para> /// Sqlite -> text<para></para>
/// </summary> /// </summary>
public int StringLength { get => _StringLength ?? 0; set => _StringLength = value; } public int StringLength { get => _StringLength ?? 0; set => _StringLength = value; }
/// <summary>
/// 执行 Insert 方法时使用此值<para></para>
/// 注意:如果是 getdate() 这种请可考虑使用 ServerTime因为它对数据库间作了适配
/// </summary>
public string InsertValueSql { get; set; }
} }
} }

View File

@ -158,5 +158,17 @@ namespace FreeSql.DataAnnotations
_column.StringLength = value; _column.StringLength = value;
return this; return this;
} }
/// <summary>
/// 执行 Insert 方法时使用此值<para></para>
/// 注意:如果是 getdate() 这种请可考虑使用 ServerTime因为它对数据库间作了适配
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public ColumnFluent InsertValueSql(string value)
{
_column.InsertValueSql = value;
return this;
}
} }
} }

View File

@ -9,16 +9,21 @@ namespace FreeSql.DataAnnotations
public class TableFluent public class TableFluent
{ {
public TableFluent(Type entityType, TableAttribute table) public TableFluent(ICodeFirst codeFirst, Type entityType, TableAttribute table)
{ {
_codeFirst = codeFirst;
_entityType = entityType; _entityType = entityType;
_properties = _entityType.GetPropertiesDictIgnoreCase(); _properties = _entityType.GetPropertiesDictIgnoreCase();
_table = table; _table = table;
} }
ICodeFirst _codeFirst;
Type _entityType; Type _entityType;
Dictionary<string, PropertyInfo> _properties; Dictionary<string, PropertyInfo> _properties;
TableAttribute _table; TableAttribute _table;
public void ConfigEntity<T2>(Action<TableFluent<T2>> fluent2) => _codeFirst.ConfigEntity<T2>(fluent2);
/// <summary> /// <summary>
/// 数据库表名 /// 数据库表名
/// </summary> /// </summary>
@ -52,6 +57,21 @@ namespace FreeSql.DataAnnotations
return new ColumnFluent(col); return new ColumnFluent(col);
} }
/// <summary>
/// 导航关系Fluent与 NavigateAttribute 对应
/// </summary>
/// <param name="proto"></param>
/// <param name="bind"></param>
/// <param name="manyToMany">多对多关系的中间实体类型</param>
/// <returns></returns>
public TableFluent Navigate(string proto, string bind, Type manyToMany = null)
{
if (_properties.TryGetValue(proto, out var tryProto) == false) throw new KeyNotFoundException($"找不到属性名 {proto}");
var nav = new NavigateAttribute { Bind = bind, ManyToMany = manyToMany };
_table._navigates.AddOrUpdate(tryProto.Name, nav, (name, old) => nav);
return this;
}
/// <summary> /// <summary>
/// 设置实体的索引 /// 设置实体的索引
/// </summary> /// </summary>
@ -70,12 +90,19 @@ namespace FreeSql.DataAnnotations
public class TableFluent<T> public class TableFluent<T>
{ {
public TableFluent(TableAttribute table) public TableFluent(ICodeFirst codeFirst, TableAttribute table)
{ {
_codeFirst = codeFirst;
_properties = typeof(T).GetPropertiesDictIgnoreCase();
_table = table; _table = table;
} }
ICodeFirst _codeFirst;
Dictionary<string, PropertyInfo> _properties;
TableAttribute _table; TableAttribute _table;
public void ConfigEntity<T2>(Action<TableFluent<T2>> fluent2) => _codeFirst.ConfigEntity<T2>(fluent2);
/// <summary> /// <summary>
/// 数据库表名 /// 数据库表名
/// </summary> /// </summary>
@ -106,7 +133,12 @@ namespace FreeSql.DataAnnotations
{ {
var proto = (column.Body as MemberExpression)?.Member; var proto = (column.Body as MemberExpression)?.Member;
if (proto == null) throw new FormatException($"错误的表达式格式 {column}"); if (proto == null) throw new FormatException($"错误的表达式格式 {column}");
var col = _table._columns.GetOrAdd(proto.Name, name => new ColumnAttribute { Name = proto.Name }); return Property(proto.Name);
}
public ColumnFluent Property(string proto)
{
if (_properties.TryGetValue(proto, out var tryProto)) throw new KeyNotFoundException($"找不到属性名 {proto}");
var col = _table._columns.GetOrAdd(tryProto.Name, name => new ColumnAttribute { Name = proto });
return new ColumnFluent(col); return new ColumnFluent(col);
} }
@ -122,8 +154,13 @@ namespace FreeSql.DataAnnotations
{ {
var member = (proto.Body as MemberExpression)?.Member; var member = (proto.Body as MemberExpression)?.Member;
if (member == null) throw new FormatException($"错误的表达式格式 {proto}"); if (member == null) throw new FormatException($"错误的表达式格式 {proto}");
return Navigate(member.Name, bind, manyToMany);
}
public TableFluent<T> Navigate(string proto, string bind, Type manyToMany = null)
{
if (_properties.TryGetValue(proto, out var tryProto) == false) throw new KeyNotFoundException($"找不到属性名 {proto}");
var nav = new NavigateAttribute { Bind = bind, ManyToMany = manyToMany }; var nav = new NavigateAttribute { Bind = bind, ManyToMany = manyToMany };
_table._navigates.AddOrUpdate(member.Name, nav, (name, old) => nav); _table._navigates.AddOrUpdate(tryProto.Name, nav, (name, old) => nav);
return this; return this;
} }
@ -140,5 +177,10 @@ namespace FreeSql.DataAnnotations
_table._indexs.AddOrUpdate(name, idx, (_, __) => idx); _table._indexs.AddOrUpdate(name, idx, (_, __) => idx);
return this; return this;
} }
public TableFluent<T> IndexRemove(string name)
{
_table._indexs.TryRemove(name, out var oldidx);
return this;
}
} }
} }

View File

@ -98,6 +98,12 @@
Sqlite -> text<para></para> Sqlite -> text<para></para>
</summary> </summary>
</member> </member>
<member name="P:FreeSql.DataAnnotations.ColumnAttribute.InsertValueSql">
<summary>
执行 Insert 方法时使用此值<para></para>
注意:如果是 getdate() 这种请可考虑使用 ServerTime因为它对数据库间作了适配
</summary>
</member>
<member name="M:FreeSql.DataAnnotations.ColumnFluent.Name(System.String)"> <member name="M:FreeSql.DataAnnotations.ColumnFluent.Name(System.String)">
<summary> <summary>
数据库列名 数据库列名
@ -198,6 +204,14 @@
Sqlite -> text<para></para> Sqlite -> text<para></para>
</summary> </summary>
</member> </member>
<member name="M:FreeSql.DataAnnotations.ColumnFluent.InsertValueSql(System.String)">
<summary>
执行 Insert 方法时使用此值<para></para>
注意:如果是 getdate() 这种请可考虑使用 ServerTime因为它对数据库间作了适配
</summary>
<param name="value"></param>
<returns></returns>
</member>
<member name="T:FreeSql.DataAnnotations.ExpressionCallAttribute"> <member name="T:FreeSql.DataAnnotations.ExpressionCallAttribute">
<summary> <summary>
自定义表达式函数解析<para></para> 自定义表达式函数解析<para></para>
@ -319,6 +333,15 @@
禁用 CodeFirst 同步结构迁移 禁用 CodeFirst 同步结构迁移
</summary> </summary>
</member> </member>
<member name="M:FreeSql.DataAnnotations.TableFluent.Navigate(System.String,System.String,System.Type)">
<summary>
导航关系Fluent与 NavigateAttribute 对应
</summary>
<param name="proto"></param>
<param name="bind"></param>
<param name="manyToMany">多对多关系的中间实体类型</param>
<returns></returns>
</member>
<member name="M:FreeSql.DataAnnotations.TableFluent.Index(System.String,System.String,System.Boolean)"> <member name="M:FreeSql.DataAnnotations.TableFluent.Index(System.String,System.String,System.Boolean)">
<summary> <summary>
设置实体的索引 设置实体的索引
@ -2224,6 +2247,137 @@
<param name="parms"></param> <param name="parms"></param>
<returns></returns> <returns></returns>
</member> </member>
<member name="M:FreeSql.IAdo.ExecuteReaderAsync(System.Func{System.Data.Common.DbDataReader,System.Threading.Tasks.Task},System.Data.CommandType,System.String,System.Data.Common.DbParameter[])">
<summary>
查询若使用读写分离查询【从库】条件cmdText.StartsWith("SELECT "),否则查询【主库】
</summary>
<param name="readerHander"></param>
<param name="cmdType"></param>
<param name="cmdText"></param>
<param name="cmdParms"></param>
</member>
<member name="M:FreeSql.IAdo.ExecuteReaderAsync(System.Func{System.Data.Common.DbDataReader,System.Threading.Tasks.Task},System.String,System.Object)">
<summary>
查询ExecuteReaderAsync(dr => {}, "select * from user where age > @age", new { age = 25 })
</summary>
<param name="cmdText"></param>
<param name="parms"></param>
</member>
<member name="M:FreeSql.IAdo.ExecuteArrayAsync(System.Data.CommandType,System.String,System.Data.Common.DbParameter[])">
<summary>
查询
</summary>
<param name="cmdText"></param>
<param name="cmdParms"></param>
</member>
<member name="M:FreeSql.IAdo.ExecuteArrayAsync(System.String,System.Object)">
<summary>
查询ExecuteArrayAsync("select * from user where age > @age", new { age = 25 })
</summary>
<param name="cmdText"></param>
<param name="parms"></param>
<returns></returns>
</member>
<member name="M:FreeSql.IAdo.ExecuteDataSetAsync(System.Data.CommandType,System.String,System.Data.Common.DbParameter[])">
<summary>
查询
</summary>
<param name="cmdText"></param>
<param name="cmdParms"></param>
</member>
<member name="M:FreeSql.IAdo.ExecuteDataSetAsync(System.String,System.Object)">
<summary>
查询ExecuteDataSetAsync("select * from user where age > @age; select 2", new { age = 25 })
</summary>
<param name="cmdText"></param>
<param name="parms"></param>
<returns></returns>
</member>
<member name="M:FreeSql.IAdo.ExecuteDataTableAsync(System.Data.CommandType,System.String,System.Data.Common.DbParameter[])">
<summary>
查询
</summary>
<param name="cmdText"></param>
<param name="cmdParms"></param>
</member>
<member name="M:FreeSql.IAdo.ExecuteDataTableAsync(System.String,System.Object)">
<summary>
查询ExecuteDataTableAsync("select * from user where age > @age", new { age = 25 })
</summary>
<param name="cmdText"></param>
<param name="parms"></param>
<returns></returns>
</member>
<member name="M:FreeSql.IAdo.ExecuteNonQueryAsync(System.Data.CommandType,System.String,System.Data.Common.DbParameter[])">
<summary>
在【主库】执行
</summary>
<param name="cmdType"></param>
<param name="cmdText"></param>
<param name="cmdParms"></param>
</member>
<member name="M:FreeSql.IAdo.ExecuteNonQueryAsync(System.String,System.Object)">
<summary>
在【主库】执行ExecuteNonQueryAsync("delete from user where age > @age", new { age = 25 })
</summary>
<param name="cmdText"></param>
<param name="parms"></param>
<returns></returns>
</member>
<member name="M:FreeSql.IAdo.ExecuteScalarAsync(System.Data.CommandType,System.String,System.Data.Common.DbParameter[])">
<summary>
在【主库】执行
</summary>
<param name="cmdType"></param>
<param name="cmdText"></param>
<param name="cmdParms"></param>
</member>
<member name="M:FreeSql.IAdo.ExecuteScalarAsync(System.String,System.Object)">
<summary>
在【主库】执行ExecuteScalarAsync("select 1 from user where age > @age", new { age = 25 })
</summary>
<param name="cmdText"></param>
<param name="parms"></param>
<returns></returns>
</member>
<member name="M:FreeSql.IAdo.QueryAsync``1(System.Data.CommandType,System.String,System.Data.Common.DbParameter[])">
<summary>
执行SQL返回对象集合QueryAsync&lt;User&gt;("select * from user where age > @age", new SqlParameter { ParameterName = "age", Value = 25 })
</summary>
<typeparam name="T"></typeparam>
<param name="cmdType"></param>
<param name="cmdText"></param>
<param name="cmdParms"></param>
<returns></returns>
</member>
<member name="M:FreeSql.IAdo.QueryAsync``1(System.String,System.Object)">
<summary>
执行SQL返回对象集合QueryAsync&lt;User&gt;("select * from user where age > @age", new { age = 25 })
</summary>
<typeparam name="T"></typeparam>
<param name="cmdText"></param>
<param name="parms"></param>
<returns></returns>
</member>
<member name="M:FreeSql.IAdo.QueryAsync``2(System.Data.CommandType,System.String,System.Data.Common.DbParameter[])">
<summary>
执行SQL返回对象集合Query&lt;User&gt;("select * from user where age > @age; select * from address", new SqlParameter { ParameterName = "age", Value = 25 })
</summary>
<typeparam name="T1"></typeparam>
<param name="cmdType"></param>
<param name="cmdText"></param>
<param name="cmdParms"></param>
<returns></returns>
</member>
<member name="M:FreeSql.IAdo.QueryAsync``2(System.String,System.Object)">
<summary>
执行SQL返回对象集合Query&lt;User&gt;("select * from user where age > @age; select * from address", new { age = 25 })
</summary>
<typeparam name="T1"></typeparam>
<param name="cmdText"></param>
<param name="parms"></param>
<returns></returns>
</member>
<member name="P:FreeSql.IAop.ParseExpression"> <member name="P:FreeSql.IAop.ParseExpression">
<summary> <summary>
可自定义解析表达式 可自定义解析表达式
@ -3002,160 +3156,3 @@
</member> </member>
</members> </members>
</doc> </doc>
unc{``0,System.Boolean}},System.Boolean,System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}})">
<summary>
使用 or 拼接两个 lambda 表达式
</summary>
<typeparam name="T"></typeparam>
<param name="exp1"></param>
<param name="condition">true 时生效</param>
<param name="exp2"></param>
<returns></returns>
</member>
<member name="M:System.Linq.Expressions.LambadaExpressionExtensions.Not``1(System.Linq.Expressions.Expression{System.Func{``0,System.Boolean}},System.Boolean)">
<summary>
将 lambda 表达式取反
</summary>
<typeparam name="T"></typeparam>
<param name="exp"></param>
<param name="condition">true 时生效</param>
<returns></returns>
</member>
<member name="M:FreeUtil.NewMongodbId">
<summary>
生成类似Mongodb的ObjectId有序、不重复Guid
</summary>
<returns></returns>
</member>
<member name="M:IFreeSql.Insert``1">
<summary>
插入数据
</summary>
<typeparam name="T1"></typeparam>
<returns></returns>
</member>
<member name="M:IFreeSql.Insert``1(``0)">
<summary>
插入数据,传入实体
</summary>
<typeparam name="T1"></typeparam>
<param name="source"></param>
<returns></returns>
</member>
<member name="M:IFreeSql.Insert``1(``0[])">
<summary>
插入数据,传入实体数组
</summary>
<typeparam name="T1"></typeparam>
<param name="source"></param>
<returns></returns>
</member>
<member name="M:IFreeSql.Insert``1(System.Collections.Generic.List{``0})">
<summary>
插入数据,传入实体集合
</summary>
<typeparam name="T1"></typeparam>
<param name="source"></param>
<returns></returns>
</member>
<member name="M:IFreeSql.Insert``1(System.Collections.Generic.IEnumerable{``0})">
<summary>
插入数据,传入实体集合
</summary>
<typeparam name="T1"></typeparam>
<param name="source"></param>
<returns></returns>
</member>
<member name="M:IFreeSql.Update``1">
<summary>
修改数据
</summary>
<typeparam name="T1"></typeparam>
<returns></returns>
</member>
<member name="M:IFreeSql.Update``1(System.Object)">
<summary>
修改数据,传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1}
</summary>
<typeparam name="T1"></typeparam>
<param name="dywhere">主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合</param>
<returns></returns>
</member>
<member name="M:IFreeSql.Select``1">
<summary>
查询数据
</summary>
<typeparam name="T1"></typeparam>
<returns></returns>
</member>
<member name="M:IFreeSql.Select``1(System.Object)">
<summary>
查询数据,传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1}
</summary>
<typeparam name="T1"></typeparam>
<param name="dywhere">主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合</param>
<returns></returns>
</member>
<member name="M:IFreeSql.Delete``1">
<summary>
删除数据
</summary>
<typeparam name="T1"></typeparam>
<returns></returns>
</member>
<member name="M:IFreeSql.Delete``1(System.Object)">
<summary>
删除数据,传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1}
</summary>
<typeparam name="T1"></typeparam>
<param name="dywhere">主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合</param>
<returns></returns>
</member>
<member name="M:IFreeSql.Transaction(System.Action)">
<summary>
开启事务不支持异步60秒未执行完成可能被其他线程事务自动提交
</summary>
<param name="handler">事务体 () => {}</param>
</member>
<member name="M:IFreeSql.Transaction(System.TimeSpan,System.Action)">
<summary>
开启事务(不支持异步)
</summary>
<param name="timeout">超时,未执行完成(可能)被其他线程事务自动提交</param>
<param name="handler">事务体 () => {}</param>
</member>
<member name="M:IFreeSql.Transaction(System.Data.IsolationLevel,System.TimeSpan,System.Action)">
<summary>
开启事务(不支持异步)
</summary>
<param name="isolationLevel"></param>
<param name="handler">事务体 () => {}</param>
<param name="timeout">超时,未执行完成(可能)被其他线程事务自动提交</param>
</member>
<member name="P:IFreeSql.Ado">
<summary>
数据库访问对象
</summary>
</member>
<member name="P:IFreeSql.Aop">
<summary>
所有拦截方法都在这里
</summary>
</member>
<member name="P:IFreeSql.CodeFirst">
<summary>
CodeFirst 模式开发相关方法
</summary>
</member>
<member name="P:IFreeSql.DbFirst">
<summary>
DbFirst 模式开发相关方法
</summary>
</member>
<member name="P:IFreeSql.GlobalFilter">
<summary>
全局过滤设置,可默认附加为 Select/Update/Delete 条件
</summary>
</member>
</members>
</doc>

View File

@ -58,7 +58,7 @@ namespace FreeSql.Internal
if (entity == null) return _orm.CodeFirst; if (entity == null) return _orm.CodeFirst;
var type = typeof(T); var type = typeof(T);
var table = dicConfigEntity.GetOrAdd(type, new TableAttribute()); var table = dicConfigEntity.GetOrAdd(type, new TableAttribute());
var fluent = new TableFluent<T>(table); var fluent = new TableFluent<T>(CodeFirst, table);
entity.Invoke(fluent); entity.Invoke(fluent);
Utils.RemoveTableByEntity(type, this); //remove cache Utils.RemoveTableByEntity(type, this); //remove cache
return _orm.CodeFirst; return _orm.CodeFirst;
@ -67,7 +67,7 @@ namespace FreeSql.Internal
{ {
if (entity == null) return _orm.CodeFirst; if (entity == null) return _orm.CodeFirst;
var table = dicConfigEntity.GetOrAdd(type, new TableAttribute()); var table = dicConfigEntity.GetOrAdd(type, new TableAttribute());
var fluent = new TableFluent(type, table); var fluent = new TableFluent(CodeFirst, type, table);
entity.Invoke(fluent); entity.Invoke(fluent);
Utils.RemoveTableByEntity(type, this); //remove cache Utils.RemoveTableByEntity(type, this); //remove cache
return _orm.CodeFirst; return _orm.CodeFirst;
@ -132,6 +132,7 @@ namespace FreeSql.Internal
if (trycol._CanUpdate != null) attr._CanUpdate = trycol.CanUpdate; if (trycol._CanUpdate != null) attr._CanUpdate = trycol.CanUpdate;
if (trycol.ServerTime != DateTimeKind.Unspecified) attr.ServerTime = trycol.ServerTime; if (trycol.ServerTime != DateTimeKind.Unspecified) attr.ServerTime = trycol.ServerTime;
if (trycol._StringLength != null) attr.StringLength = trycol.StringLength; if (trycol._StringLength != null) attr.StringLength = trycol.StringLength;
if (!string.IsNullOrEmpty(trycol.InsertValueSql)) attr.InsertValueSql = trycol.InsertValueSql;
} }
var attrs = proto.GetCustomAttributes(typeof(ColumnAttribute), false); var attrs = proto.GetCustomAttributes(typeof(ColumnAttribute), false);
foreach (var tryattrobj in attrs) foreach (var tryattrobj in attrs)
@ -152,6 +153,7 @@ namespace FreeSql.Internal
if (tryattr._CanUpdate != null) attr._CanUpdate = tryattr.CanUpdate; if (tryattr._CanUpdate != null) attr._CanUpdate = tryattr.CanUpdate;
if (tryattr.ServerTime != DateTimeKind.Unspecified) attr.ServerTime = tryattr.ServerTime; if (tryattr.ServerTime != DateTimeKind.Unspecified) attr.ServerTime = tryattr.ServerTime;
if (tryattr._StringLength != null) attr.StringLength = tryattr.StringLength; if (tryattr._StringLength != null) attr.StringLength = tryattr.StringLength;
if (!string.IsNullOrEmpty(tryattr.InsertValueSql)) attr.InsertValueSql = tryattr.InsertValueSql;
} }
ColumnAttribute ret = null; ColumnAttribute ret = null;
if (!string.IsNullOrEmpty(attr.Name)) ret = attr; if (!string.IsNullOrEmpty(attr.Name)) ret = attr;
@ -168,6 +170,7 @@ namespace FreeSql.Internal
if (attr._CanUpdate != null) ret = attr; if (attr._CanUpdate != null) ret = attr;
if (attr.ServerTime != DateTimeKind.Unspecified) ret = attr; if (attr.ServerTime != DateTimeKind.Unspecified) ret = attr;
if (attr._StringLength != null) ret = attr; if (attr._StringLength != null) ret = attr;
if (!string.IsNullOrEmpty(attr.InsertValueSql)) ret = attr;
if (ret != null && ret.MapType == null) ret.MapType = proto.PropertyType; if (ret != null && ret.MapType == null) ret.MapType = proto.PropertyType;
return ret; return ret;
} }

View File

@ -191,6 +191,11 @@ namespace FreeSql.Internal
col.DbDefaultValue = colattr.ServerTime == DateTimeKind.Local ? common.Now : common.NowUtc; col.DbDefaultValue = colattr.ServerTime == DateTimeKind.Local ? common.Now : common.NowUtc;
col.DbInsertValue = colattr.ServerTime == DateTimeKind.Local ? common.Now : common.NowUtc; col.DbInsertValue = colattr.ServerTime == DateTimeKind.Local ? common.Now : common.NowUtc;
} }
if (string.IsNullOrEmpty(colattr.InsertValueSql) == false)
{
col.DbDefaultValue = colattr.InsertValueSql;
col.DbInsertValue = colattr.InsertValueSql;
}
if (colattr.MapType == typeof(string) && colattr.StringLength != 0) if (colattr.MapType == typeof(string) && colattr.StringLength != 0)
{ {
int strlen = colattr.StringLength; int strlen = colattr.StringLength;