Skip to content

Commit

Permalink
Tracking fix (#3)
Browse files Browse the repository at this point in the history
* Fixed issue where entities were still being tracked after save
  • Loading branch information
TieDyeGeek authored Aug 25, 2020
1 parent cfb92da commit a4dd7a8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<PackageId>CSESoftware.Repository.EntityFrameworkCore</PackageId>
<Authors>CSE Software, Inc.</Authors>
<Copyright>2020 CSE Software, Inc.</Copyright>
<Version>2.0.0</Version>
<Version>2.0.1</Version>
<PackageIcon>packageIcon.png</PackageIcon>
<PackageIconUrl />
<Description>The Entity Framework Core implementation of CSESoftware.Repository.</Description>
Expand Down
23 changes: 16 additions & 7 deletions src/CSESoftware.Repository.EntityFrameworkCore/Repository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,17 @@ public virtual void Update<TEntity>(TEntity entity)
where TEntity : class, IEntity
{
entity.UpdateSetup();
Context.Set<TEntity>().Attach(entity);
if (Context.Entry(entity).State == EntityState.Detached)
Context.Set<TEntity>().Attach(entity);

Context.Entry(entity).State = EntityState.Modified;
}

public virtual void Update<TEntity>(List<TEntity> entities)
where TEntity : class, IEntity
{
Context.Set<TEntity>().AttachRange(entities);
Context.Set<TEntity>().AttachRange(
entities.Where(x => Context.Entry(x).State == EntityState.Detached));

foreach (var entity in entities)
{
Expand All @@ -62,9 +65,8 @@ public virtual void Delete<TEntity>(TEntity entity)
{
var dbSet = Context.Set<TEntity>();
if (Context.Entry(entity).State == EntityState.Detached)
{
dbSet.Attach(entity);
}

dbSet.Remove(entity);
}

Expand All @@ -83,9 +85,16 @@ public virtual void Delete<TEntity>(Expression<Func<TEntity, bool>> filter)
Context.Set<TEntity>().RemoveRange(Context.Set<TEntity>().Where(filter));
}

public virtual Task SaveAsync()
public virtual async Task SaveAsync()
{
await Context.SaveChangesAsync();
DetachAllEntities();
}

private void DetachAllEntities()
{
return Context.SaveChangesAsync();
Context.ChangeTracker.Entries().ToList()
.ForEach(x => x.State = EntityState.Detached);
}
}
}
}

0 comments on commit a4dd7a8

Please sign in to comment.