From ae0936aae7181aac73e3e9efc9121994ee652714 Mon Sep 17 00:00:00 2001 From: Pete Forrest Date: Fri, 5 May 2023 16:58:22 +0100 Subject: [PATCH] Fix InsertOrUpdate inserting second record when there are no dirty properties --- Dashing.IntegrationTests/Tests/AsyncTests.cs | 11 +++++++++++ Dashing/Session.Extensions..cs | 18 ++++++++++++------ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/Dashing.IntegrationTests/Tests/AsyncTests.cs b/Dashing.IntegrationTests/Tests/AsyncTests.cs index 43dc273a..0512134d 100644 --- a/Dashing.IntegrationTests/Tests/AsyncTests.cs +++ b/Dashing.IntegrationTests/Tests/AsyncTests.cs @@ -36,5 +36,16 @@ public async Task InsertWorks(TestSessionWrapper wrapper) { await wrapper.Session.InsertAsync(comment); Assert.NotEqual(0, comment.CommentId); } + + [Theory] + [MemberData(nameof(SessionDataGenerator.GetSessions), MemberType = typeof(SessionDataGenerator))] + public async Task InsertOrUpdateWorks(TestSessionWrapper wrapper) { + const string CommentContent = "Foo InsertOrUpdate"; + var comment = new Comment { Content = CommentContent }; + await wrapper.Session.InsertOrUpdateAsync(comment); + await wrapper.Session.InsertOrUpdateAsync(comment); + var comments = await wrapper.Session.Query().Where(c => c.Content == CommentContent).ToListAsync(); + Assert.Equal(1, comments.Count); + } } } \ No newline at end of file diff --git a/Dashing/Session.Extensions..cs b/Dashing/Session.Extensions..cs index d2d13745..59a2f85a 100644 --- a/Dashing/Session.Extensions..cs +++ b/Dashing/Session.Extensions..cs @@ -153,9 +153,12 @@ public int Delete(params Expression>[] predicates) public int InsertOrUpdate(T entity, Expression> equalityComparer = null) where T : class, new() { if (equalityComparer == null) { - // if the equality comparer is null then they should be passing us a valid PK value in the entity so call update - var updated = this.Save(entity); - return updated == 0 ? this.Insert(entity) : updated; + // if the entity has previously come from the DB tracking will be enabled + if (((ITrackedEntity)entity).IsTrackingEnabled()) { + return this.Save(entity); + } + + return this.Insert(entity); } // we support different equalityComparers so we can cope with e.g. username @@ -317,9 +320,12 @@ public Task DeleteAsync(params Expression>[] predicates) public async Task InsertOrUpdateAsync(T entity, Expression> equalityComparer = null) where T : class, new() { if (equalityComparer == null) { - // if the equality comparer is null then they should be passing us a valid PK value in the entity so call update - var updated = await this.SaveAsync(entity); - return updated == 0 ? await this.InsertAsync(entity) : updated; + // if the entity has previously come from the DB tracking will be enabled + if (((ITrackedEntity)entity).IsTrackingEnabled()) { + return await this.SaveAsync(entity); + } + + return await this.InsertAsync(entity); } // we support different equalityComparers so we can cope with e.g. username