Skip to content

Commit 298da21

Browse files
authored
Merge pull request #53 from bing-framework/hotfix/dev_3.1-orm_update
fix: 修复 更新时,导航属性丢失问题
2 parents a8df853 + 95a92b5 commit 298da21

File tree

1 file changed

+41
-10
lines changed

1 file changed

+41
-10
lines changed

framework/src/Bing.Datas.EntityFramework/Core/StoreBase.cs

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@
55
using System.Threading.Tasks;
66
using Bing.Data;
77
using Bing.Domain.Entities;
8+
using Bing.Exceptions;
9+
using Bing.Extensions;
810
using Bing.Uow;
911
using Microsoft.EntityFrameworkCore;
12+
using Microsoft.EntityFrameworkCore.ChangeTracking;
1013

1114
namespace Bing.Datas.EntityFramework.Core
1215
{
@@ -98,21 +101,49 @@ public virtual async Task AddAsync(IEnumerable<TEntity> entities, CancellationTo
98101
/// <exception cref="ArgumentNullException"></exception>
99102
public virtual void Update(TEntity entity)
100103
{
101-
if (entity == null)
102-
throw new ArgumentNullException(nameof(entity));
103-
UnitOfWork.Entry(entity).State = EntityState.Detached;
104-
var old = Find(entity.Id);
105-
var oldEntry = UnitOfWork.Entry(old);
106-
if (!(entity is IVersion version))
104+
entity.CheckNull(nameof(entity));
105+
var entry = UnitOfWork.Entry(entity);
106+
ValidateVersion(entry, entity);
107+
UpdateEntity(entry, entity);
108+
}
109+
110+
/// <summary>
111+
/// 验证版本号
112+
/// </summary>
113+
/// <param name="entry">输入实体</param>
114+
/// <param name="entity">实体</param>
115+
protected void ValidateVersion(EntityEntry<TEntity> entry, TEntity entity)
116+
{
117+
if (entry.State == EntityState.Detached)
118+
return;
119+
if (entity is not IVersion current)
120+
return;
121+
if (current.Version == null)
122+
return;
123+
var oldVersion = entry.OriginalValues.GetValue<byte[]>(nameof(IVersion.Version));
124+
for (var i = 0; i < oldVersion.Length; i++)
125+
{
126+
if (current.Version[i] != oldVersion[i])
127+
throw new ConcurrencyException($"Type:{typeof(TEntity)},Id:{entity.Id}");
128+
}
129+
}
130+
131+
/// <summary>
132+
/// 更新实体
133+
/// </summary>
134+
/// <param name="entry">输入实体</param>
135+
/// <param name="entity">实体</param>
136+
protected void UpdateEntity(EntityEntry<TEntity> entry, TEntity entity)
137+
{
138+
var oldEntry = UnitOfWork.ChangeTracker.Entries<TEntity>().FirstOrDefault(x => x.Entity.Equals(entity));
139+
if (oldEntry != null)
107140
{
108141
oldEntry.CurrentValues.SetValues(entity);
109142
return;
110143
}
111144

112-
oldEntry.State = EntityState.Detached;
113-
oldEntry.CurrentValues[nameof(version.Version)] = version.Version;
114-
oldEntry = UnitOfWork.Attach(old);
115-
oldEntry.CurrentValues.SetValues(entity);
145+
if (entry.State == EntityState.Detached)
146+
UnitOfWork.Update(entity);
116147
}
117148

118149
/// <summary>

0 commit comments

Comments
 (0)