Skip to content

Commit 17cca52

Browse files
authored
Fix identity column handling for generated GUIDs on SQL server and add corresponding tests (#54)
1 parent b79b2b5 commit 17cca52

4 files changed

Lines changed: 26 additions & 21 deletions

File tree

src/PhenX.EntityFrameworkCore.BulkInsert.SqlServer/SqlServerDialectBuilder.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ public override string BuildMoveDataSql<T>(
3434
{
3535
var q = new StringBuilder();
3636

37-
if (options.CopyGeneratedColumns)
37+
var identityInsert = options.CopyGeneratedColumns && insertedColumns.Any(x => x.IsGenerated);
38+
if (identityInsert)
3839
{
3940
q.AppendLine($"SET IDENTITY_INSERT {target.QuotedTableName} ON;");
4041
}
@@ -129,7 +130,7 @@ public override string BuildMoveDataSql<T>(
129130

130131
q.AppendLine(";");
131132

132-
if (options.CopyGeneratedColumns)
133+
if (identityInsert)
133134
{
134135
q.AppendLine($"SET IDENTITY_INSERT {target.QuotedTableName} OFF;");
135136
}

src/PhenX.EntityFrameworkCore.BulkInsert/Metadata/ColumnMetadata.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ internal sealed class ColumnMetadata(IProperty property, SqlDialectBuilder dial
2222

2323
public Type ClrType { get; } = property.ClrType;
2424

25-
public bool IsGenerated { get; } = property.ValueGenerated == ValueGenerated.OnAdd;
25+
public bool IsGenerated { get; } = property.ValueGenerated != ValueGenerated.Never;
2626

2727
public object? GetValue(object entity, BulkInsertOptions options)
2828
{

tests/PhenX.EntityFrameworkCore.BulkInsert.Tests/DbContext/TestEntityWithGeneratedGuidId.cs

Lines changed: 0 additions & 18 deletions
This file was deleted.

tests/PhenX.EntityFrameworkCore.BulkInsert.Tests/Tests/Basic/BasicTestsBase.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,4 +261,26 @@ await _context.ExecuteBulkInsertAsync(entities, (SqlServerBulkInsertOptions _) =
261261
}));
262262
}
263263
}
264+
265+
[SkippableTheory]
266+
[CombinatorialData]
267+
public async Task InsertEntities_WithGeneratedGuidId(InsertStrategy strategy)
268+
{
269+
// Arrange
270+
var entities = new List<TestEntityWithGuidId>
271+
{
272+
new TestEntityWithGuidId { Id = Guid.NewGuid(), Name = $"{_run}_Entity1" },
273+
new TestEntityWithGuidId { Id = Guid.NewGuid(), Name = $"{_run}_Entity2" }
274+
};
275+
276+
// Act
277+
var insertedEntities = await _context.InsertWithStrategyAsync(strategy, entities, configure => configure.CopyGeneratedColumns = true);
278+
279+
// Assert
280+
insertedEntities.Should().BeEquivalentTo(entities,
281+
o=> o
282+
.RespectingRuntimeTypes()
283+
.Excluding(e => e.Id)
284+
);
285+
}
264286
}

0 commit comments

Comments
 (0)