public virtual async Task SaveChanges_uses_ambient_transaction(bool async, bool closeConnection, bool autoTransactionsEnabled)
        {
            if (!AmbientTransactionsSupported)
            {
                return;
            }

            if (closeConnection)
            {
                TestStore.CloseConnection();
            }
            else if (TestStore.ConnectionState == ConnectionState.Closed)
            {
                TestStore.OpenConnection();
            }

            using (TestUtilities.TestStore.CreateTransactionScope())
            {
                using (var context = CreateContext())
                {
                    context.Database.AutoTransactionsEnabled = autoTransactionsEnabled;

                    context.Add(
                        new TransactionCustomer
                    {
                        Id   = 77,
                        Name = "Bobble"
                    });

                    // Issue #14935. Cannot eval 'Last()'
                    // Use AsEnumerable().
                    context.Entry(context.Set <TransactionCustomer>().AsEnumerable().Last()).State = EntityState.Added;

                    if (async)
                    {
                        await Assert.ThrowsAsync <DbUpdateException>(() => context.SaveChangesAsync());
                    }
                    else
                    {
                        Assert.Throws <DbUpdateException>(() => context.SaveChanges());
                    }

                    context.Database.AutoTransactionsEnabled = true;
                }

                Assert.Equal(
                    RelationalResources.LogAmbientTransactionEnlisted(new TestLogger <RelationalLoggingDefinitions>()).GenerateMessage("Serializable"),
                    Fixture.ListLoggerFactory.Log.First().Message);
            }

            if (closeConnection)
            {
                using (var context = CreateContext())
                {
                    context.Database.OpenConnection();
                }
            }

            AssertStoreInitialState();
        }
        public virtual async Task SaveChanges_uses_enlisted_transaction(bool async, bool autoTransactionsEnabled)
        {
            using (var transaction = new CommittableTransaction(TimeSpan.FromMinutes(10)))
            {
                using (var context = CreateContext())
                {
                    context.Database.EnlistTransaction(transaction);
                    context.Database.AutoTransactionsEnabled = autoTransactionsEnabled;

                    context.Add(
                        new TransactionCustomer {
                        Id = 77, Name = "Bobble"
                    });

                    context.Entry(context.Set <TransactionCustomer>().OrderBy(c => c.Id).Last()).State = EntityState.Added;

                    if (async)
                    {
                        await Assert.ThrowsAsync <DbUpdateException>(() => context.SaveChangesAsync());
                    }
                    else
                    {
                        Assert.Throws <DbUpdateException>(() => context.SaveChanges());
                    }

                    context.Database.AutoTransactionsEnabled = true;
                }

                if (AmbientTransactionsSupported)
                {
                    Assert.Equal(
                        RelationalResources.LogExplicitTransactionEnlisted(new TestLogger <TestRelationalLoggingDefinitions>())
                        .GenerateMessage("Serializable"),
                        Fixture.ListLoggerFactory.Log.First().Message);
                }
                else
                {
                    Assert.Equal(
                        RelationalResources.LogAmbientTransaction(new TestLogger <TestRelationalLoggingDefinitions>()).GenerateMessage(),
                        Fixture.ListLoggerFactory.Log.First().Message);

                    if (!autoTransactionsEnabled)
                    {
                        using var context = CreateContext();
                        context.Entry(context.Set <TransactionCustomer>().Single(c => c.Id == 77)).State = EntityState.Deleted;

                        if (async)
                        {
                            await context.SaveChangesAsync();
                        }
                        else
                        {
                            context.SaveChanges();
                        }
                    }
                }
            }

            AssertStoreInitialState();
        }
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        public virtual InterceptionResult ConnectionOpening(
            IRelationalConnection connection,
            DateTimeOffset startTime)
        {
            _suppressOpenExpiration = startTime + _loggingCacheTime;

            var definition = RelationalResources.LogOpeningConnection(this);

            if (ShouldLog(definition))
            {
                _suppressOpenExpiration = default;

                definition.Log(this, connection.DbConnection.Database, connection.DbConnection.DataSource);
            }

            if (NeedsEventData <IDbConnectionInterceptor>(
                    definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled))
            {
                _suppressOpenExpiration = default;

                var eventData = BroadcastConnectionOpening(
                    connection,
                    startTime,
                    definition,
                    async: false,
                    diagnosticSourceEnabled,
                    simpleLogEnabled);

                if (interceptor != null)
                {
                    return(interceptor.ConnectionOpening(connection.DbConnection, eventData, default));
                }
            }

            return(default);
        public virtual void Detects_primary_key_with_default_value()
        {
            var model   = CreateConventionlessModelBuilder().Model;
            var entityA = model.AddEntityType(typeof(A));

            SetPrimaryKey(entityA);
            entityA.FindProperty("Id").Relational().DefaultValue = 1;

            VerifyWarning(RelationalResources.LogKeyHasDefaultValue(new TestLogger <RelationalLoggingDefinitions>()).GenerateMessage("Id", "A"), model);
        }
Exemple #5
0
 public virtual void LastOrDefault_without_order_by_issues_client_eval_warning()
 {
     using (var context = CreateContext())
     {
         Assert.Equal(
             CoreStrings.WarningAsErrorTemplate(
                 RelationalEventId.QueryClientEvaluationWarning,
                 RelationalResources.LogClientEvalWarning(new TestLogger <RelationalLoggingDefinitions>()).GenerateMessage("LastOrDefault()"),
                 "RelationalEventId.QueryClientEvaluationWarning"),
             Assert.Throws <InvalidOperationException>(
                 () => context.Customers.LastOrDefault()).Message);
     }
 }
Exemple #6
0
 public virtual void Throws_when_warning_as_error()
 {
     using (var context = CreateContext())
     {
         Assert.Equal(
             CoreStrings.WarningAsErrorTemplate(
                 RelationalEventId.QueryClientEvaluationWarning,
                 RelationalResources.LogClientEvalWarning(new TestLogger <RelationalLoggingDefinitions>()).GenerateMessage("where [c].IsLondon"),
                 "RelationalEventId.QueryClientEvaluationWarning"),
             Assert.Throws <InvalidOperationException>(
                 () => context.Customers.Where(c => c.IsLondon).ToList()).Message);
     }
 }
Exemple #7
0
 public virtual void Warning_when_suspicious_conversion_in_sql()
 {
     using (var context = CreateContext())
     {
         Assert.Contains(
             RelationalResources.LogValueConversionSqlLiteralWarning(new TestLogger <SqlServerLoggingDefinitions>())
             .GenerateMessage(
                 typeof(decimal).ShortDisplayName(),
                 new NumberToBytesConverter <decimal>().GetType().ShortDisplayName()),
             Assert.Throws <InvalidOperationException>(
                 () =>
                 context.Set <BuiltInDataTypes>().Where(b => b.TestDecimal > 123.0m).ToList()).Message);
     }
 }
Exemple #8
0
        public virtual void Detects_alternate_key_with_default_value()
        {
            var model   = CreateConventionlessModelBuilder().Model;
            var entityA = model.AddEntityType(typeof(A));

            SetPrimaryKey(entityA);

            var property = entityA.AddProperty("P0", typeof(int?));

            property.IsNullable = false;
            entityA.AddKey(new[] { property });
            property.SetDefaultValue(1);

            VerifyWarning(RelationalResources.LogKeyHasDefaultValue(new TestLogger <TestRelationalLoggingDefinitions>()).GenerateMessage("P0", "A"), model);
        }
Exemple #9
0
        public void Migrations_ignores_the_unattributed()
        {
            var logger = new TestLogger <DbLoggerCategory.Migrations, TestRelationalLoggingDefinitions> {
                EnabledFor = LogLevel.Warning
            };
            var assembly = CreateMigrationsAssembly(logger);

            var result = assembly.Migrations;

            Assert.Equal(2, result.Count);
            Assert.DoesNotContain(result, t => t.GetType() == typeof(MigrationWithoutAttribute));
            Assert.Equal(
                RelationalResources.LogMigrationAttributeMissingWarning(logger).GenerateMessage(nameof(MigrationWithoutAttribute)),
                logger.Message);
        }
Exemple #10
0
 public virtual void Last_with_order_by_issues_client_eval_warning_in_subquery()
 {
     using (var context = CreateContext())
     {
         Assert.Equal(
             CoreStrings.WarningAsErrorTemplate(
                 RelationalEventId.QueryClientEvaluationWarning,
                 RelationalResources.LogClientEvalWarning(new TestLogger <RelationalLoggingDefinitions>()).GenerateMessage("Last()"),
                 "RelationalEventId.QueryClientEvaluationWarning"),
             Assert.Throws <InvalidOperationException>(
                 () => context.Customers
                 .Where(
                     c => c.CustomerID == "ALFKI" &&
                     c.Orders.OrderBy(o => o.OrderID).Last().OrderID > 1000).ToList()).Message);
     }
 }
Exemple #11
0
        public virtual ModelBuilder Default_for_key_string_column_throws()
        {
            var modelBuilder = CreateModelBuilder();

            modelBuilder.Entity <Login1>().Property(l => l.UserName).HasDefaultValue("default");
            modelBuilder.Ignore <Profile1>();

            Assert.Equal(
                CoreStrings.WarningAsErrorTemplate(
                    RelationalEventId.ModelValidationKeyDefaultValueWarning,
                    RelationalResources.LogKeyHasDefaultValue(new TestLogger <SqlServerLoggingDefinitions>()).GenerateMessage(nameof(Login1.UserName), nameof(Login1)),
                    "RelationalEventId.ModelValidationKeyDefaultValueWarning"),
                Assert.Throws <InvalidOperationException>(() => Validate(modelBuilder)).Message);

            return(modelBuilder);
        }
Exemple #12
0
        public virtual void Detects_bool_with_default_expression()
        {
            var model      = CreateConventionlessModelBuilder().Model;
            var entityType = model.AddEntityType(typeof(E));

            SetPrimaryKey(entityType);
            entityType.AddProperty("ImNot", typeof(bool?)).SetDefaultValueSql("TRUE");
            entityType.AddProperty("ImNotUsed", typeof(bool)).SetDefaultValueSql("TRUE");

            var property = entityType.AddProperty("ImBool", typeof(bool));

            property.SetDefaultValueSql("TRUE");
            property.ValueGenerated = ValueGenerated.OnAddOrUpdate;

            VerifyWarning(RelationalResources.LogBoolWithDefaultWarning(new TestLogger <TestRelationalLoggingDefinitions>()).GenerateMessage("ImBool", "E"), model);
        }
Exemple #13
0
    /// <summary>
    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
    ///     any release. You should only use it directly in your code with extreme caution and knowing that
    ///     doing so can result in application failures when updating to a new Entity Framework Core release.
    /// </summary>
    public virtual InterceptionResult <DbCommand> CommandCreating(
        IRelationalConnection connection,
        DbCommandMethod commandMethod,
        DbContext?context,
        Guid commandId,
        Guid connectionId,
        DateTimeOffset startTime,
        CommandSource commandSource)
    {
        _suppressCommandCreateExpiration = startTime + _loggingCacheTime;

        var definition = RelationalResources.LogCommandCreating(this);

        if (ShouldLog(definition))
        {
            _suppressCommandCreateExpiration = default;

            definition.Log(this, commandMethod.ToString());
        }

        if (NeedsEventData <IDbCommandInterceptor>(
                definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled))
        {
            _suppressCommandCreateExpiration = default;

            var eventData = BroadcastCommandCreating(
                connection.DbConnection,
                context,
                commandMethod,
                commandId,
                connectionId,
                async: false,
                startTime,
                definition,
                diagnosticSourceEnabled,
                simpleLogEnabled,
                commandSource);

            if (interceptor != null)
            {
                return(interceptor.CommandCreating(eventData, default));
            }
        }

        return(default);
Exemple #14
0
        public void SqlServerValueGenerationStrategy_warns_when_setting_conflicting_DefaultValue(
            SqlServerValueGenerationStrategy sqlServerValueGenerationStrategy)
        {
            var modelBuilder = CreateConventionalModelBuilder();

            var propertyBuilder = modelBuilder.Entity <Dog>().Property <int>("Id");

            propertyBuilder.Metadata.SetValueGenerationStrategy(sqlServerValueGenerationStrategy);
            ConfigureProperty(propertyBuilder.Metadata, "DefaultValue", "2");

            VerifyWarnings(new[] {
                SqlServerResources.LogConflictingValueGenerationStrategies(new TestLogger <SqlServerLoggingDefinitions>())
                .GenerateMessage(sqlServerValueGenerationStrategy.ToString(), "DefaultValue", "Id", nameof(Dog)),
                RelationalResources.LogKeyHasDefaultValue(new TestLogger <SqlServerLoggingDefinitions>())
                .GenerateMessage("Id", nameof(Dog))
            },
                           modelBuilder.Model);
        }
        public override async Task Average_on_float_column_in_subquery(bool isAsync)
        {
            await base.Average_on_float_column_in_subquery(isAsync);

            AssertContainsSql(
                @"SELECT [o].[OrderID]
FROM [Orders] AS [o]
WHERE [o].[OrderID] < 10300",
                //
                @"@_outer_OrderID='10248'

SELECT CAST(AVG([od0].[Discount]) AS real)
FROM [Order Details] AS [od0]
WHERE @_outer_OrderID = [od0].[OrderID]");

            Assert.Contains(
                RelationalResources.LogQueryPossibleExceptionWithAggregateOperatorWarning(new TestLogger <SqlServerLoggingDefinitions>()).GenerateMessage(),
                Fixture.TestSqlLoggerFactory.Log.Select(l => l.Message));
        }
Exemple #16
0
        public void Inserts_are_batched_only_when_necessary(int minBatchSize)
        {
            var expectedBlogs = new List <Blog>();

            TestHelpers.ExecuteWithStrategyInTransaction(
                () => (BloggingContext)Fixture.CreateContext(minBatchSize),
                UseTransaction,
                context =>
            {
                var owner = new Owner();
                context.Owners.Add(owner);

                for (var i = 1; i < 4; i++)
                {
                    var blog = new Blog {
                        Id = Guid.NewGuid(), Owner = owner
                    };

                    context.Set <Blog>().Add(blog);
                    expectedBlogs.Add(blog);
                }

                Fixture.TestSqlLoggerFactory.Clear();

                context.SaveChanges();

                Assert.Contains(
                    minBatchSize == 3
                            ? RelationalResources.LogBatchReadyForExecution(new TestLogger <SqlServerLoggingDefinitions>())
                    .GenerateMessage(3)
                            : RelationalResources.LogBatchSmallerThanMinBatchSize(new TestLogger <SqlServerLoggingDefinitions>())
                    .GenerateMessage(3, 4),
                    Fixture.TestSqlLoggerFactory.Log.Select(l => l.Message));

                Assert.Equal(minBatchSize <= 3 ? 2 : 4, Fixture.TestSqlLoggerFactory.SqlStatements.Count);
            }, context => AssertDatabaseState(context, false, expectedBlogs));
        }
        public virtual async Task SaveChanges_uses_ambient_transaction(bool async, bool autoTransactionsEnabled)
        {
            if (TestStore.ConnectionState == ConnectionState.Closed)
            {
                TestStore.OpenConnection();
            }

            using (TestUtilities.TestStore.CreateTransactionScope())
            {
                using (var context = CreateContext())
                {
                    context.Database.AutoTransactionsEnabled = autoTransactionsEnabled;

                    context.Add(
                        new TransactionCustomer {
                        Id = 77, Name = "Bobble"
                    });

                    context.Entry(context.Set <TransactionCustomer>().OrderBy(c => c.Id).Last()).State = EntityState.Added;

                    if (async)
                    {
                        await Assert.ThrowsAsync <DbUpdateException>(() => context.SaveChangesAsync());
                    }
                    else
                    {
                        Assert.Throws <DbUpdateException>(() => context.SaveChanges());
                    }

                    context.Database.AutoTransactionsEnabled = true;
                }

                if (AmbientTransactionsSupported)
                {
                    Assert.Equal(
                        RelationalResources.LogAmbientTransactionEnlisted(new TestLogger <TestRelationalLoggingDefinitions>())
                        .GenerateMessage("Serializable"),
                        Fixture.ListLoggerFactory.Log.Skip(2).First().Message);
                }
                else
                {
                    Assert.Equal(
                        RelationalResources.LogAmbientTransaction(new TestLogger <TestRelationalLoggingDefinitions>()).GenerateMessage(),
                        Fixture.ListLoggerFactory.Log.Skip(2).First().Message);

                    using (var context = CreateContext())
                    {
                        context.Entry(context.Set <TransactionCustomer>().Single(c => c.Id == 77)).State = EntityState.Deleted;

                        if (async)
                        {
                            await context.SaveChangesAsync();
                        }
                        else
                        {
                            context.SaveChanges();
                        }
                    }
                }
            }

            AssertStoreInitialState();
        }