public void CheckHasIdentity(DbContext context) { int hasIdentity = 0; if (HasSinglePrimaryKey) { var sqlConnection = context.Database.GetDbConnection(); var currentTransaction = context.Database.CurrentTransaction; try { if (currentTransaction == null) { if (sqlConnection.State != ConnectionState.Open) { sqlConnection.Open(); } } using (var command = sqlConnection.CreateCommand()) { if (currentTransaction != null) { command.Transaction = currentTransaction.GetDbTransaction(); } command.CommandText = SqlQueryBuilder.SelectIsIdentity(FullTableName, PrimaryKeys[0]); using (var reader = command.ExecuteReader()) { if (reader.HasRows) { while (reader.Read()) { hasIdentity = reader[0] == DBNull.Value ? 0 : (int)reader[0]; } } } } } finally { if (currentTransaction == null) { sqlConnection.Close(); } } } HasIdentity = hasIdentity == 1; }
public async Task CheckHasIdentityAsync(DbContext context) { int hasIdentity = 0; if (HasSinglePrimaryKey) { var sqlConnection = context.Database.GetDbConnection(); var currentTransaction = context.Database.CurrentTransaction; try { if (currentTransaction == null) { if (sqlConnection.State != ConnectionState.Open) { await sqlConnection.OpenAsync().ConfigureAwait(false); } } using (var command = sqlConnection.CreateCommand()) { if (currentTransaction != null) { command.Transaction = currentTransaction.GetDbTransaction(); } command.CommandText = SqlQueryBuilder.SelectIsIdentity(FullTableName, PrimaryKeys[0]); using (var reader = await command.ExecuteReaderAsync().ConfigureAwait(false)) { if (reader.HasRows) { while (await reader.ReadAsync().ConfigureAwait(false)) { hasIdentity = (int)reader[0]; } } } } } finally { if (currentTransaction == null) { sqlConnection.Close(); } } } HasIdentity = hasIdentity == 1; }