- 修复 DbContext DbSet 属性初始并发时未触发 OnModelCreating;#1333

This commit is contained in:
2881099 2022-11-13 23:07:49 +08:00
parent bb57b1ffd2
commit fe5a8fc355

View File

@ -83,20 +83,29 @@ namespace FreeSql
#region Set #region Set
static ConcurrentDictionary<Type, NativeTuple<PropertyInfo[], bool>> _dicGetDbSetProps = new ConcurrentDictionary<Type, NativeTuple<PropertyInfo[], bool>>(); static ConcurrentDictionary<Type, NativeTuple<PropertyInfo[], bool>> _dicGetDbSetProps = new ConcurrentDictionary<Type, NativeTuple<PropertyInfo[], bool>>();
static object _lockOnModelCreating = new object();
internal void InitPropSets() internal void InitPropSets()
{ {
var thisType = this.GetType(); var thisType = this.GetType();
var dicval = _dicGetDbSetProps.GetOrAdd(thisType, tp => var isOnModelCreating = false;
NativeTuple.Create( if (_dicGetDbSetProps.TryGetValue(thisType, out var dicval) == false)
tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public) {
lock (_lockOnModelCreating)
{
if (_dicGetDbSetProps.TryGetValue(thisType, out dicval) == false)
{
dicval = NativeTuple.Create(
thisType.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
.Where(a => a.PropertyType.IsGenericType && .Where(a => a.PropertyType.IsGenericType &&
a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GetGenericArguments()[0])).ToArray(), a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GetGenericArguments()[0])).ToArray(),
false)); false);
if (dicval.Item2 == false) _dicGetDbSetProps.TryAdd(thisType, dicval);
{ isOnModelCreating = true;
if (_dicGetDbSetProps.TryUpdate(thisType, NativeTuple.Create(dicval.Item1, true), dicval))
OnModelCreating(OrmOriginal.CodeFirst);
} }
}
}
if (isOnModelCreating)
OnModelCreating(OrmOriginal.CodeFirst);
foreach (var prop in dicval.Item1) foreach (var prop in dicval.Item1)
{ {