public void DbSet_FindAsync_does_not_deadlock()
 {
     using (var context = new SimpleModelContext())
     {
         RunDeadlockTest(() => context.Products.FindAsync(0));
     }
 }
 public void DbQuery_ToListAsync_does_not_deadlock()
 {
     using (var context = new SimpleModelContext())
     {
         RunDeadlockTest(context.Products.ToListAsync);
     }
 }
 public void Database_ExecuteSqlCommandAsync_does_not_deadlock()
 {
     using (var context = new SimpleModelContext())
     {
         RunDeadlockTest(() => context.Database.ExecuteSqlCommandAsync("select Id from Products"));
     }
 }
Example #4
0
        public void Explicit_rollback_can_be_used_to_rollback_a_transaction()
        {
            EnsureDatabaseInitialized(() => new SimpleModelContext());

            using (var tx = new TransactionScope())
            {
                using (var context = new SimpleModelContext())
                {
                    var product = new Product
                                      {
                                          Name = "BestTea"
                                      };
                    context.Products.Add(product);
                    context.SaveChanges();

                    Assert.Equal(1, GetTransactionCount(context.Database.Connection));
                    Assert.True(context.Products.Where(p => p.Name == "BestTea").AsNoTracking().Any());

                    // Rollback System Transaction
                    tx.Dispose();

                    Assert.False(context.Products.Where(p => p.Name == "BestTea").AsNoTracking().Any());
                }
            }
        }
        public void DatabaseLogger_can_append_to_a_file()
        {
            using (var context = new SimpleModelContext())
            {
                var output = CaptureFileOutput(
                    f =>
                    {
                        using (var logger = new DatabaseLogger(f, append: false))
                        {
                            logger.StartLogging();

                            context.Categories.ToArray();
                        }

                        using (var logger = new DatabaseLogger(f, append: true))
                        {
                            logger.StartLogging();

                            context.Products.ToArray();
                        }
                    });

                Assert.Contains("FROM [dbo].[Categories]", output);
                Assert.Contains("FROM [dbo].[Products]", output);
            }
        }
        public void Logging_can_be_started_and_stopped()
        {
            using (var context = new SimpleModelContext())
            {
                var output = CaptureConsoleOutput(
                    () =>
                    {
                        using (var logger = new DatabaseLogger())
                        {
                            context.Products.ToArray();

                            logger.StartLogging();
                            logger.StopLogging();

                            context.Products.ToArray();

                            logger.StartLogging();

                            context.Categories.ToArray();

                            logger.StopLogging();

                            context.Products.ToArray();
                        }
                    });

                var foundIndex = output.IndexOf("FROM [dbo].[Categories]");
                Assert.True(foundIndex > 0);
                foundIndex = output.IndexOf("FROM [dbo].[Categories]", foundIndex + 1);
                Assert.Equal(-1, foundIndex);

                Assert.DoesNotContain("FROM [dbo].[Products]", output);
            }
        }
        public void Expression_from_static_method_with_variable()
        {
            using (var context = new SimpleModelContext())
            {
                var products = context.Products.Where(StaticExpressions.MethodWithVariable());

                Assert.DoesNotThrow(() => products.ToList());
            }
        }
        public void Expression_from_static_delegate_with_parameter()
        {
            using (var context = new SimpleModelContext())
            {
                var products = context.Products.Where(StaticExpressions.DelegateWithParameter(1));

                Assert.DoesNotThrow(() => products.ToList());
            }
        }
        public void SqlQuery_ToListAsync_does_not_deadlock()
        {
            using (var context = new SimpleModelContext())
            {
                var query = context.Database.SqlQuery<int>("select Id from Products");

                RunDeadlockTest(query.ToListAsync);
            }
        }
        public void Expression_from_static_property()
        {
            using (var context = new SimpleModelContext())
            {
                var products = context.Products.Where(StaticExpressions.Property);

                Assert.DoesNotThrow(() => products.ToList());
            }
        }
 public void Sets_are_initialized_using_name_constructor_on_DbContext()
 {
     using (var context = new SimpleModelContext(DefaultDbName<SimpleModelContext>()))
     {
         Assert.NotNull(context.Products);
         Assert.NotNull(context.Categories);
         context.Assert<Product>().IsInModel();
         context.Assert<Category>().IsInModel();
     }
 }
Example #12
0
 public void DbContext_SaveChangesAsync_does_not_deadlock()
 {
     using (var context = new SimpleModelContext())
     {
         using (context.Database.BeginTransaction())
         {
             context.Products.Add(new Product());
             RunDeadlockTest(context.SaveChangesAsync);
         }
     }
 }
        [Fact] // CodePlex 1751
        public void Joining_to_named_type_projection_typed_as_DbQuery_is_handled_correctly()
        {
            using (var context = new SimpleModelContext())
            {
                var products = (DbQuery<MeIzNamed>)context.Products.Select(p => new MeIzNamed { Id = p.Id });

                var query = context.Categories.Select(c => c.Products.Join(products, o => o.Id, i => i.Id, (o, i) => new { o, i }));

                Assert.Equal(4, query.ToList().Count);
            }
        }
        public void Expression_from_variable()
        {
            Expression<Func<Product, bool>> testExpression = p => p.Id == 1;

            using (var context = new SimpleModelContext())
            {
                var products = context.Products.Where(testExpression);

                Assert.DoesNotThrow(() => products.ToList());
            }
        }
        public void Large_union_all_should_not_give_query_nested_too_deeply()
        {
            var query = "{" + string.Join(", ", Enumerable.Range(1, 100)) + "}";

            using (var db = new SimpleModelContext(SimpleCeConnection<SimpleModelContext>()))
            {
                using (var reader = QueryTestHelpers.EntityCommandSetup(db, query))
                {
                    VerifyAgainstBaselineResults(reader, Enumerable.Range(1, 100));
                }
            }
        }
        public void Initialization_hooks_are_run_once_on_EF_initialization_in_the_app_domain()
        {
            // Make sure that EF has been used if this happens to be the first test run
            using (var context = new SimpleModelContext())
            {
                context.Database.Initialize(force: false);
            }

            Assert.Equal(
                new[] { "Hook1()", "Hook1(2013, 'December 31')", "Hook2()", "Hook2('January 1', 2014)", "Hook2()", "Hook1(4102, '1 yraunaJ')", "Hook1()" },
                TestLoadedInterceptor.HooksRun.ToArray().Reverse());
        }
        public void DbEntityEntry_Member_works_for_collections_under_partial_trust()
        {
            using (var context = new SimpleModelContext())
            {
                var category = context.Categories.First();

                var collection = context.Entry(category).Member<ICollection<Product>>("Products");

                Assert.NotNull(collection);
                Assert.IsType<DbCollectionEntry<Category, Product>>(collection);
            }
        }
Example #18
0
 public void DbEntityEntry_ReloadAsync_does_not_deadlock()
 {
     using (var context = new SimpleModelContext())
     {
         RunDeadlockTest(
             async () =>
                 {
                     await context.Products.LoadAsync().ConfigureAwait(false);
                     await context.ChangeTracker.Entries().First().ReloadAsync().ConfigureAwait(false);
                 });
     }
 }
        [Fact] // CodePlex 1751
        public void Joining_to_anonymous_type_projection_is_handled_correctly()
        {
            using (var context = new SimpleModelContext())
            {
                var products = context.Products.Select(p => new { p.Id });

                var query = context.Categories.Select(
                    c => c.Products
                             .Join(products, o => o.Id, i => i.Id, (o, i) => new { o, i }));

                Assert.Equal(4, query.ToList().Count);
            }
        }
 public void Sets_are_initialized_using_existing_connection_constructor_on_DbContext()
 {
     using (var connection = SimpleConnection<SimpleModelContext>())
     {
         using (var context = new SimpleModelContext(connection))
         {
             Assert.NotNull(context.Products);
             Assert.NotNull(context.Categories);
             context.Assert<Product>().IsInModel();
             context.Assert<Category>().IsInModel();
         }
     }
 }
        public void Edmx_can_be_written_from_a_context_created_using_DbCompiledModel()
        {
            var edmxBuilder = new StringBuilder();
            var model = SimpleModelContext.CreateBuilder().Build(ProviderRegistry.Sql2008_ProviderInfo).Compile();
            using (var context = new SimpleModelContext(model))
            {
                EdmxWriter.WriteEdmx(context, XmlWriter.Create(edmxBuilder));

                // Quick sanity check that the context is still usable.
                Assert.NotNull(context.Products.Find(1));
            }

            SanityCheckEdmx(edmxBuilder);
        }
        public void EDMX_can_be_written_multiple_times()
        {
            var edmxBuilders = new[] { new StringBuilder(), new StringBuilder(), new StringBuilder() };
            using (var context = new SimpleModelContext())
            {
                EdmxWriter.WriteEdmx(context, XmlWriter.Create(edmxBuilders[0]));

                context.Database.Initialize(force: false);

                EdmxWriter.WriteEdmx(context, XmlWriter.Create(edmxBuilders[1]));
                EdmxWriter.WriteEdmx(context, XmlWriter.Create(edmxBuilders[2]));
            }

            edmxBuilders.ToList().ForEach(SanityCheckEdmx);
        }
        [Fact] // CodePlex 1751
        public void Joining_to_named_type_projection_using_ObjectQuery_is_handled_correctly()
        {
            using (var context = new SimpleModelContext())
            {
                var objectContext = ((IObjectContextAdapter)context).ObjectContext;

                var products = objectContext.CreateObjectSet<Product>().Select(p => new MeIzNamed { Id = p.Id });

                var query =
                    objectContext.CreateObjectSet<Category>()
                        .Select(c => c.Products.Join(products, o => o.Id, i => i.Id, (o, i) => new { o, i }));

                Assert.Equal(4, query.ToList().Count);
            }
        }
        public void Negated_null_comparison_is_converted_to_CASE_with_single_ISNULL_statement()
        {
            using (var context = new SimpleModelContext())
            {
                var actualSql = context.Products.Select(p => p.Name != null);

                const string expectedSql =
@"SELECT 
    CASE WHEN ([Extent1].[Name] IS NOT NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C1]
    FROM [dbo].[Products] AS [Extent1]
    WHERE [Extent1].[Discriminator] IN (N'FeaturedProduct',N'Product')";

                QueryTestHelpers.VerifyDbQuery(actualSql, expectedSql);
            }
        }
Example #25
0
 public void DbContext_SaveChangesAsync_does_not_deadlock()
 {
     ExtendedSqlAzureExecutionStrategy.ExecuteNew(
         () =>
         {
             using (var context = new SimpleModelContext())
             {
                 using (context.Database.BeginTransaction())
                 {
                     context.Products.Add(new Product());
                     RunDeadlockTest(context.SaveChangesAsync);
                 }
             }
         });
 }
        public void Insert_In_SystemTransaction_without_commit_works_and_transaction_count_is_correct()
        {
            EnsureDatabaseInitialized(() => new SimpleModelContext());

            using (new TransactionScope())
            {
                using (var context = new SimpleModelContext())
                {
                    var product = new Product { Name = "Fanta" };
                    context.Products.Add(product);
                    context.SaveChanges();

                    Assert.Equal(1, GetTransactionCount(context.Database.Connection));
                    Assert.True(context.Products.Where(p => p.Name == "Fanta").AsNoTracking().Any());
                }
            }
        }
        private void EDMX_can_be_written(bool initializeContext)
        {
            var edmxBuilder = new StringBuilder();
            using (var context = new SimpleModelContext())
            {
                if (initializeContext)
                {
                    context.Database.Initialize(force: false);
                }

                EdmxWriter.WriteEdmx(context, XmlWriter.Create(edmxBuilder));

                // Quick sanity check that the context is still usable.
                Assert.NotNull(context.Products.Find(1));
            }

            SanityCheckEdmx(edmxBuilder);
        }
        public void Any_with_predicate_is_converted_to_CASE_with_single_EXISTS_statement()
        {
            using (var context = new SimpleModelContext())
            {
                var actualSql = context.Categories.Select(c => c.Products.Any(p => p.Id > 10));

                const string expectedSql = 
@"SELECT 
    CASE WHEN ( EXISTS (SELECT 
        1 AS [C1]
        FROM [dbo].[Products] AS [Extent2]
        WHERE ([Extent2].[Discriminator] IN (N'FeaturedProduct',N'Product')) AND ([Extent1].[Id] = [Extent2].[CategoryId]) AND ([Extent2].[Id] > 10)
    )) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C1]
    FROM [dbo].[Categories] AS [Extent1]";

                QueryTestHelpers.VerifyDbQuery(actualSql, expectedSql);
            }
        }
Example #29
0
        public void DatabaseLogger_can_log_to_a_file()
        {
            Assert.Contains(
                "FROM [dbo].[Products]",
                CaptureFileOutput(
                    f =>
                    {
                        using (var logger = new DatabaseLogger(f))
                        {
                            using (var context = new SimpleModelContext())
                            {
                                logger.StartLogging();

                                context.Products.ToArray();
                            }
                        }
                    }));
        }
        public void Scenario_Find()
        {
            using (var context = new SimpleModelContext())
            {
                var product = context.Products.Find(1);
                var category = context.Categories.Find("Foods");

                // Scenario ends; simple validation of final state follows
                Assert.NotNull(product);
                Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State);

                Assert.NotNull(category);
                Assert.Equal(EntityState.Unchanged, GetStateEntry(context, category).State);

                Assert.Equal("Foods", product.CategoryId);
                Assert.Same(category, product.Category);
                Assert.True(category.Products.Contains(product));
            }
        }