initial commit

This commit is contained in:
tk
2024-11-13 18:18:28 +08:00
commit 013f35e296
1500 changed files with 443723 additions and 0 deletions

View File

@ -0,0 +1,61 @@
using FreeSql.DataAnnotations;
namespace FreeSql.Extensions.EfCoreFluentApi
{
public class EfCoreColumnFluent
{
ColumnFluent _cf;
internal EfCoreColumnFluent(ColumnFluent tf)
{
_cf = tf;
}
/// <summary>
/// 使用 FreeSql FluentApi 方法,当 EFCore FluentApi 方法无法表示的时候使用
/// </summary>
/// <returns></returns>
public ColumnFluent Help() => _cf;
public EfCoreColumnFluent HasColumnName(string name)
{
_cf.Name(name);
return this;
}
public EfCoreColumnFluent HasColumnType(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;
//}
public EfCoreColumnFluent HasPrecision(int precision, int scale = 0)
{
_cf.Precision(precision, scale);
return this;
}
}
}

View File

@ -0,0 +1,138 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using FreeSql;
using FreeSql.DataAnnotations;
using FreeSql.Extensions.EfCoreFluentApi;
using FreeSql.Internal.CommonProvider;
partial class FreeSqlDbContextExtensions
{
/// <summary>
/// EFCore 95% 相似的 FluentApi 扩展方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="codeFirst"></param>
/// <param name="modelBuilder"></param>
/// <returns></returns>
public static ICodeFirst Entity<T>(this ICodeFirst codeFirst, Action<EfCoreTableFluent<T>> modelBuilder)
{
var cf = codeFirst as CodeFirstProvider;
codeFirst.ConfigEntity<T>(tf => modelBuilder(new EfCoreTableFluent<T>(cf._orm, tf)));
return codeFirst;
}
/// <summary>
/// EFCore 95% 相似的 FluentApi 扩展方法
/// </summary>
/// <param name="codeFirst"></param>
/// <param name="entityType">实体类型</param>
/// <param name="modelBuilder"></param>
/// <returns></returns>
public static ICodeFirst Entity(this ICodeFirst codeFirst, Type entityType, Action<EfCoreTableFluent> modelBuilder)
{
var cf = codeFirst as CodeFirstProvider;
codeFirst.ConfigEntity(entityType, tf => modelBuilder(new EfCoreTableFluent(cf._orm, tf, entityType)));
return codeFirst;
}
public static ICodeFirst ApplyConfiguration<TEntity>(this ICodeFirst codeFirst, IEntityTypeConfiguration<TEntity> configuration) where TEntity : class
{
return codeFirst.Entity<TEntity>(eb =>
{
configuration.Configure(eb);
});
}
#if net40
#else
static IEnumerable<MethodInfo> GetExtensionMethods(this Assembly assembly, Type extendedType)
{
var query = from type in assembly.GetTypes()
where !type.IsGenericType && !type.IsNested
from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
where method.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute), false)
where method.GetParameters()[0].ParameterType == extendedType
select method;
return query;
}
/// <summary>
/// 根据Assembly扫描所有继承IEntityTypeConfiguration&lt;T&gt;的配置类
/// </summary>
/// <param name="codeFirst"></param>
/// <param name="assembly"></param>
/// <param name="predicate"></param>
/// <returns></returns>
public static ICodeFirst ApplyConfigurationsFromAssembly(this ICodeFirst codeFirst, Assembly assembly, Func<Type, bool> predicate = null)
{
IEnumerable<TypeInfo> typeInfos = assembly.DefinedTypes.Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition);
MethodInfo methodInfo = typeof(FreeSqlDbContextExtensions).Assembly.GetExtensionMethods(typeof(ICodeFirst))
.Single((e) => e.Name == "Entity" && e.ContainsGenericParameters);
if (methodInfo == null) return codeFirst;
foreach (TypeInfo constructibleType in typeInfos)
{
if (constructibleType.GetConstructor(Type.EmptyTypes) == null || predicate != null && !predicate(constructibleType))
{
continue;
}
foreach (var @interface in constructibleType.GetInterfaces())
{
if (@interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))
{
var type = @interface.GetGenericArguments().First();
var efFluentType = typeof(EfCoreTableFluent<>).MakeGenericType(type);
var actionType = typeof(Action<>).MakeGenericType(efFluentType);
//1.需要实体和Configuration配置
//codeFirst.Entity<ToDoItem>(eb =>
//{
// new ToDoItemConfiguration().Configure(eb);
//});
//2.需要实体
//Action<EfCoreTableFluent<ToDoItem>> x = new Action<EfCoreTableFluent<ToDoItem>>(e =>
//{
// object o = Activator.CreateInstance(constructibleType);
// constructibleType.GetMethod("ApplyConfiguration")?.Invoke(o, new object[1] { e });
//});
//codeFirst.Entity<ToDoItem>(x);
//3.实现动态调用泛型委托
DelegateBuilder delegateBuilder = new DelegateBuilder(constructibleType);
MethodInfo applyconfigureMethod = delegateBuilder.GetType().GetMethod("ApplyConfiguration")?.MakeGenericMethod(type);
if (applyconfigureMethod == null) continue;
Delegate @delegate = Delegate.CreateDelegate(actionType, delegateBuilder, applyconfigureMethod);
methodInfo.MakeGenericMethod(type).Invoke(null, new object[2]
{
codeFirst,
@delegate
});
}
}
}
return codeFirst;
}
class DelegateBuilder
{
private readonly Type type;
public DelegateBuilder(Type type)
{
this.type = type;
}
public void ApplyConfiguration<T>(EfCoreTableFluent<T> ex)
{
object o = Activator.CreateInstance(type);
type.GetMethod("Configure")?.Invoke(o, new object[1] { ex });
}
}
#endif
}

View File

@ -0,0 +1,278 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using FreeSql.DataAnnotations;
namespace FreeSql.Extensions.EfCoreFluentApi
{
public class EfCoreTableFluent
{
IFreeSql _fsql;
TableFluent _tf;
internal Type _entityType;
internal EfCoreTableFluent(IFreeSql fsql, TableFluent tf, Type entityType)
{
_fsql = fsql;
_tf = tf;
_entityType = entityType;
}
public EfCoreTableFluent ToTable(string name)
{
_tf.Name(name);
return this;
}
public EfCoreTableFluent ToView(string name)
{
_tf.DisableSyncStructure(true);
_tf.Name(name);
return this;
}
public EfCoreColumnFluent Property(string property) => new EfCoreColumnFluent(_tf.Property(property));
/// <summary>
/// 使用 FreeSql FluentApi 方法,当 EFCore FluentApi 方法无法表示的时候使用
/// </summary>
/// <returns></returns>
public TableFluent Help() => _tf;
#region HasKey
public EfCoreTableFluent HasKey(string key)
{
if (key == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("key"));
foreach (string name in key.Split(','))
{
if (string.IsNullOrEmpty(name.Trim())) continue;
_tf.Property(name.Trim()).IsPrimary(true);
}
return this;
}
#endregion
#region HasIndex
public HasIndexFluent HasIndex(string index)
{
if (index == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("index"));
var indexName = $"idx_{Guid.NewGuid().ToString("N").Substring(0, 8)}";
var columns = new List<string>();
foreach (string name in index.Split(','))
{
if (string.IsNullOrEmpty(name.Trim())) continue;
columns.Add(name.Trim());
}
_tf.Index(indexName, string.Join(", ", columns), false);
return new HasIndexFluent(_tf, indexName, columns);
}
public class HasIndexFluent
{
TableFluent _modelBuilder;
string _indexName;
List<string> _columns;
bool _isUnique;
internal HasIndexFluent(TableFluent 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 HasOne(string 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
{
IFreeSql _fsql;
TableFluent _tf;
Type _entityType1;
Type _entityType2;
string _selfProperty;
string _selfBind;
string _withManyProperty;
string _withOneProperty;
string _withOneBind;
internal HasOneFluent(IFreeSql fsql, TableFluent modelBuilder, Type entityType1, Type entityType2, string oneProperty)
{
_fsql = fsql;
_tf = modelBuilder;
_entityType1 = entityType1;
_entityType2 = entityType2;
_selfProperty = oneProperty;
}
public HasOneFluent WithMany(string 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));
return this;
}
public HasOneFluent WithOne(string one, string foreignKey)
{
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(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(DbContextStrings.ParameterError("foreignKey"));
_withOneBind = _withOneBind.TrimStart(',', ' ');
if (string.IsNullOrEmpty(_selfBind) == false)
_fsql.CodeFirst.ConfigEntity(_entityType2, eb2 => eb2.Navigate(_withOneProperty, _withOneBind));
return this;
}
public HasOneFluent HasForeignKey(string foreignKey)
{
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(DbContextStrings.ParameterError("foreignKey"));
_selfBind = _selfBind.TrimStart(',', ' ');
_tf.Navigate(_selfProperty, _selfBind);
if (string.IsNullOrEmpty(_withManyProperty) == false)
_fsql.CodeFirst.ConfigEntity(_entityType2, eb2 => eb2.Navigate(_withManyProperty, _selfBind));
if (string.IsNullOrEmpty(_withOneProperty) == false && string.IsNullOrEmpty(_withOneBind) == false)
_fsql.CodeFirst.ConfigEntity(_entityType2, eb2 => eb2.Navigate(_withOneProperty, _withOneBind));
return this;
}
}
#endregion
#region HasMany
public HasManyFluent HasMany(string 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
{
IFreeSql _fsql;
TableFluent _tf;
Type _entityType1;
Type _entityType2;
string _selfProperty;
string _selfBind;
string _withOneProperty;
string _withManyProperty;
internal HasManyFluent(IFreeSql fsql, TableFluent modelBuilder, Type entityType1, Type entityType2, string manyProperty)
{
_fsql = fsql;
_tf = modelBuilder;
_entityType1 = entityType1;
_entityType2 = entityType2;
_selfProperty = manyProperty;
}
public void WithMany(string many, Type middleType)
{
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(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));
return this;
}
public HasManyFluent HasForeignKey(string foreignKey)
{
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(DbContextStrings.ParameterError("foreignKey"));
_selfBind = _selfBind.TrimStart(',', ' ');
_tf.Navigate(_selfProperty, _selfBind);
if (string.IsNullOrEmpty(_withOneProperty) == false)
_fsql.CodeFirst.ConfigEntity(_entityType2, eb2 => eb2.Navigate(_withOneProperty, _selfBind));
return this;
}
}
#endregion
public EfCoreTableFluent Ignore(string property)
{
_tf.Property(property).IsIgnore(true);
return this;
}
/// <summary>
/// 使用 Repository + EnableCascadeSave + NoneParameter 方式插入种子数据
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public EfCoreTableFluent HasData(IEnumerable<object> data)
{
if (data.Any() == false) return this;
var sdCopy = data.Select(a => (object)a).ToList();
var sdCopyLock = new object();
_fsql.Aop.SyncStructureAfter += new EventHandler<Aop.SyncStructureAfterEventArgs>((s, e) =>
{
object[] sd = null;
lock (sdCopyLock)
sd = sdCopy?.ToArray();
if (sd == null || sd.Any() == false) return;
foreach (var et in e.EntityTypes)
{
if (et != _entityType) continue;
if (_fsql.Select<object>().AsType(et).Any()) continue;
var repo = _fsql.GetRepository<object>();
repo.DbContextOptions.EnableCascadeSave = true;
repo.DbContextOptions.NoneParameter = true;
repo.AsType(et);
repo.Insert(sd);
lock (sdCopyLock)
sdCopy = null;
}
});
return this;
}
}
}

View File

@ -0,0 +1,365 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using FreeSql.DataAnnotations;
namespace FreeSql.Extensions.EfCoreFluentApi
{
public class EfCoreTableFluent<T>
{
IFreeSql _fsql;
TableFluent<T> _tf;
internal EfCoreTableFluent(IFreeSql fsql, TableFluent<T> tf)
{
_fsql = fsql;
_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));
/// <summary>
/// 使用 FreeSql FluentApi 方法,当 EFCore FluentApi 方法无法表示的时候使用
/// </summary>
/// <returns></returns>
public TableFluent<T> Help() => _tf;
#region HasKey
public EfCoreTableFluent<T> HasKey(Expression<Func<T, object>> key)
{
var exp = key?.Body;
if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand;
if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("key"));
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)
{
var exp = index?.Body;
if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand;
if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("index"));
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)
{
var exp = one?.Body;
if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand;
if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("one"));
var oneProperty = "";
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
oneProperty = (exp as MemberExpression).Member.Name;
break;
}
if (string.IsNullOrEmpty(oneProperty)) throw new ArgumentException(DbContextStrings.ParameterError("one"));
return new HasOneFluent<T2>(_fsql, _tf, oneProperty);
}
public class HasOneFluent<T2>
{
IFreeSql _fsql;
TableFluent<T> _tf;
string _selfProperty;
string _selfBind;
string _withManyProperty;
string _withOneProperty;
string _withOneBind;
internal HasOneFluent(IFreeSql fsql, TableFluent<T> modelBuilder, string oneProperty)
{
_fsql = fsql;
_tf = modelBuilder;
_selfProperty = oneProperty;
}
public HasOneFluent<T2> WithMany<TMany>(Expression<Func<T2, TMany>> many)
{
var exp = many?.Body;
if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand;
if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("many"));
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
_withManyProperty = (exp as MemberExpression).Member.Name;
break;
}
if (string.IsNullOrEmpty(_withManyProperty)) throw new ArgumentException(DbContextStrings.ParameterError("many"));
if (string.IsNullOrEmpty(_selfBind) == false)
_fsql.CodeFirst.ConfigEntity<T2>(eb2 => eb2.Navigate(_withManyProperty, _selfBind));
return this;
}
public HasOneFluent<T2> WithOne(Expression<Func<T2, T>> one, Expression<Func<T2, object>> foreignKey)
{
var exp = one?.Body;
if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand;
if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("one"));
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
_withOneProperty = (exp as MemberExpression).Member.Name;
break;
}
if (string.IsNullOrEmpty(_withOneProperty)) throw new ArgumentException(DbContextStrings.ParameterError("one"));
exp = foreignKey?.Body;
if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand;
if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("foreignKey"));
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(DbContextStrings.ParameterError("foreignKey"));
if (string.IsNullOrEmpty(_selfBind) == false)
_fsql.CodeFirst.ConfigEntity<T2>(eb2 => eb2.Navigate(_withOneProperty, _withOneBind));
return this;
}
public HasOneFluent<T2> HasForeignKey(Expression<Func<T, object>> foreignKey)
{
var exp = foreignKey?.Body;
if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand;
if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("foreignKey"));
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(DbContextStrings.ParameterError("foreignKey"));
_tf.Navigate(_selfProperty, _selfBind);
if (string.IsNullOrEmpty(_withManyProperty) == false)
_fsql.CodeFirst.ConfigEntity<T2>(eb2 => eb2.Navigate(_withManyProperty, _selfBind));
if (string.IsNullOrEmpty(_withOneProperty) == false && string.IsNullOrEmpty(_withOneBind) == false)
_fsql.CodeFirst.ConfigEntity<T2>(eb2 => eb2.Navigate(_withOneProperty, _withOneBind));
return this;
}
}
#endregion
#region HasMany
public HasManyFluent<T2> HasMany<T2>(Expression<Func<T, IEnumerable<T2>>> many)
{
var exp = many?.Body;
if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand;
if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("many"));
var manyProperty = "";
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
manyProperty = (exp as MemberExpression).Member.Name;
break;
}
if (string.IsNullOrEmpty(manyProperty)) throw new ArgumentException(DbContextStrings.ParameterError("many"));
return new HasManyFluent<T2>(_fsql, _tf, manyProperty);
}
public class HasManyFluent<T2>
{
IFreeSql _fsql;
TableFluent<T> _tf;
string _selfProperty;
string _selfBind;
string _withOneProperty;
string _withManyProperty;
internal HasManyFluent(IFreeSql fsql, TableFluent<T> modelBuilder, string manyProperty)
{
_fsql = fsql;
_tf = modelBuilder;
_selfProperty = manyProperty;
}
public void WithMany(Expression<Func<T2, IEnumerable<T>>> many, Type middleType)
{
var exp = many?.Body;
if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand;
if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("many"));
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
_withManyProperty = (exp as MemberExpression).Member.Name;
break;
}
if (string.IsNullOrEmpty(_withManyProperty)) throw new ArgumentException(DbContextStrings.ParameterError("many"));
_tf.Navigate(_selfProperty, null, middleType);
_fsql.CodeFirst.ConfigEntity<T2>(eb2 => eb2.Navigate(_withManyProperty, null, middleType));
}
public HasManyFluent<T2> WithOne(Expression<Func<T2, T>> one)
{
var exp = one?.Body;
if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand;
if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("one"));
switch (exp.NodeType)
{
case ExpressionType.MemberAccess:
_withOneProperty = (exp as MemberExpression).Member.Name;
break;
}
if (string.IsNullOrEmpty(_withOneProperty)) throw new ArgumentException(DbContextStrings.ParameterError("one"));
if (string.IsNullOrEmpty(_selfBind) == false)
_fsql.CodeFirst.ConfigEntity<T2>(eb2 => eb2.Navigate(_withOneProperty, _selfBind));
return this;
}
public HasManyFluent<T2> HasForeignKey(Expression<Func<T2, object>> foreignKey)
{
var exp = foreignKey?.Body;
if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand;
if (exp == null) throw new ArgumentException(DbContextStrings.ParameterError_CannotBeNull("foreignKey"));
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(DbContextStrings.ParameterError("foreignKey"));
_tf.Navigate(_selfProperty, _selfBind);
if (string.IsNullOrEmpty(_withOneProperty) == false)
_fsql.CodeFirst.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 });
/// <summary>
/// 使用 Repository + EnableCascadeSave + NoneParameter 方式插入种子数据
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public EfCoreTableFluent<T> HasData(IEnumerable<T> data)
{
if (data.Any() == false) return this;
var sdCopy = data.Select(a => (object)a).ToList();
var sdCopyLock = new object();
_fsql.Aop.SyncStructureAfter += new EventHandler<Aop.SyncStructureAfterEventArgs>((s, e) =>
{
object[] sd = null;
lock (sdCopyLock)
sd = sdCopy?.ToArray();
if (sd == null || sd.Any() == false) return;
foreach (var et in e.EntityTypes)
{
if (et != typeof(T)) continue;
if (_fsql.Select<object>().AsType(et).Any()) continue;
var repo = _fsql.GetRepository<object>();
repo.DbContextOptions.EnableCascadeSave = true;
repo.DbContextOptions.NoneParameter = true;
repo.AsType(et);
repo.Insert(sd);
lock (sdCopyLock)
sdCopy = null;
}
});
return this;
}
}
}

View File

@ -0,0 +1,7 @@
namespace FreeSql.Extensions.EfCoreFluentApi
{
public interface IEntityTypeConfiguration<TEntity> where TEntity : class
{
void Configure(EfCoreTableFluent<TEntity> model);
}
}