public static void Handling_optional_dependents_sharing_table_with_principal_1()
    {
        Console.WriteLine($">>>> Sample: {nameof(Handling_optional_dependents_sharing_table_with_principal_1)}");
        Console.WriteLine();

        Helpers.RecreateCleanDatabase();

        using (var context = new SomeDbContext())
        {
            var principal = new PrincipalWithOptionalDependents();
            context.Add(principal);

            Console.WriteLine("Saving principal with all null dependent objects:");
            Console.WriteLine($"  Dependent with only optional properties is {(principal.DependentWithOnlyOptionalProperties != null ? "not " : "")}null.");
            Console.WriteLine($"  Dependent with only required properties is {(principal.DependentWithOnlyRequiredProperties != null ? "not " : "")}null.");
            Console.WriteLine($"  Dependent with both optional and required properties is {(principal.DependentWithOptionalAndRequiredProperties != null ? "not " : "")}null.");

            context.SaveChanges();
        }

        using (var context = new SomeDbContext())
        {
            var principal = context.PrincipalsWithOptionalDependents.Single();
            Console.WriteLine("After querying back principal and dependents saved above:");
            Console.WriteLine($"  Dependent with only optional properties is {(principal.DependentWithOnlyOptionalProperties != null ? "not " : "")}null.");
            Console.WriteLine($"  Dependent with only required properties is {(principal.DependentWithOnlyRequiredProperties != null ? "not " : "")}null.");
            Console.WriteLine($"  Dependent with both optional and required properties is {(principal.DependentWithOptionalAndRequiredProperties != null ? "not " : "")}null.");
        }

        Console.WriteLine();
    }
Пример #2
0
        public async Task Setup()
        {
            _cancel = new CancellationTokenSource(10_000);

            using (var connection =
                       new NpgsqlConnection("Server=localhost;Port=5432;Database=postgres;User Id=postgres;Password=Test123!"))
            {
                await connection.OpenAsync(_cancel.Token);

                await connection.ExecuteAsync(
                    "DROP TABLE IF EXISTS public.\"SomeEntity\"; CREATE TABLE public.\"SomeEntity\" (\"Id\" integer not null, \"Name\" varchar(8) not null);" +
                    "DROP TABLE IF EXISTS public.\"Child1Entity\"; DROP TABLE IF EXISTS public.\"Child2Entity\"; DROP TABLE IF EXISTS public.\"ParentEntity\";" +
                    "CREATE TABLE public.\"ParentEntity\" (\"Id\" integer not null primary key, \"Name\" varchar(8) not null);" +
                    "CREATE TABLE public.\"Child1Entity\" (\"Id\" integer not null, \"Modified\" timestamp not null, \"ParentId\" integer not null, FOREIGN KEY(\"ParentId\") REFERENCES public.\"ParentEntity\"(\"Id\"));" +
                    "CREATE TABLE public.\"Child2Entity\" (\"Id\" integer not null, \"Modified\" timestamp not null, \"ParentId\" integer not null, FOREIGN KEY(\"ParentId\") REFERENCES public.\"ParentEntity\"(\"Id\"));" +
                    "INSERT INTO public.\"ParentEntity\" (\"Id\", \"Name\") values (1, 'test1');" +
                    "INSERT INTO public.\"Child1Entity\" (\"Id\", \"ParentId\", \"Modified\") values (1, 1, CURRENT_TIMESTAMP);" +
                    "INSERT INTO public.\"Child2Entity\" (\"Id\", \"ParentId\", \"Modified\") values (1, 1, CURRENT_TIMESTAMP);",
                    _cancel.Token);
            }

            dbContext = new SomeDbContext(new DbContextOptionsBuilder <SomeDbContext>()
                                          .UseNpgsql("Server=localhost;Port=5432;Database=postgres;User Id=postgres;Password=Test123!")
                                          .UseLockModifiers()
                                          .UseLoggerFactory(LoggerFactory.Create(builder =>
                                                                                 builder
                                                                                 .SetMinimumLevel(LogLevel.Error)
                                                                                 .AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Information)
                                                                                 .AddNUnit()))
                                          .Options);
        }
    public static void Array_parameters_are_logged_in_readable_form()
    {
        Console.WriteLine($">>>> Sample: {nameof(Array_parameters_are_logged_in_readable_form)}");
        Console.WriteLine();

        Helpers.RecreateCleanDatabase();

        using var context = new SomeDbContext();

        try
        {
            context.Database.ExecuteSqlRaw(
                "SELECT * FROM Blogs WHERE Data = {0}",
                new SqlParameter
            {
                DbType = DbType.String, Value = new[] { "First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh" }
            });
        }
        catch
        {
            // Exception is expected as array parameters are not valid on SQL Server.
            // However, log output shows the parameter logging.
            //
            // dbug: 8/2/2021 11:34:16.880 RelationalEventId.CommandExecuting[20100] (Microsoft.EntityFrameworkCore.Database.Command)
            // Executing DbCommand [Parameters=[@p0={ 'First', 'Second', 'Third', 'Fourth', 'Fifth', ... } (Nullable = false) (DbType = String)], CommandType='Text', CommandTimeout='30']
            // SELECT * FROM Blogs WHERE Data = @p0
        }

        Console.WriteLine();
    }
Пример #4
0
    public async Task Counts_when_DbUpdateConcurrencyException_is_thrown(bool async)
    {
        TotalOptimisticConcurrencyFailures = 0;

        for (var i = 1; i <= 3; i++)
        {
            using var context = new SomeDbContext();

            var entity = new Foo();
            context.Add(entity);
            context.SaveChanges();

            using (var innerContext = new SomeDbContext())
            {
                innerContext.Foos.Find(entity.Id).Token = 1;
                innerContext.SaveChanges();
            }

            entity.Token = 2;

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

            Assert.Equal(i, TotalOptimisticConcurrencyFailures);
        }
    }
 public async Task Setup()
 {
     dbContext = new SomeDbContext(new DbContextOptionsBuilder <SomeDbContext>()
                                   .UseNpgsql("Server=localhost")
                                   .UseLockModifiers()
                                   .Options);
 }
        public static void RecreateCleanDatabase()
        {
            using var context = new SomeDbContext(quiet: true);

            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();
        }
Пример #7
0
        public void Throws_for_comparer_with_wrong_type()
        {
            using var context = new SomeDbContext();

            Assert.Equal(
                CoreStrings.ComparerPropertyMismatch("double", nameof(Foo), nameof(Foo.Bar), "int"),
                Assert.Throws <InvalidOperationException>(() => context.Model).Message);
        }
    public static void Optional_dependents_without_a_required_property()
    {
        Console.WriteLine($">>>> Sample: {nameof(Optional_dependents_without_a_required_property)}");
        Console.WriteLine();

        Helpers.RecreateCleanDatabase();

        using (var context = new SomeDbContext())
        {
            #region AllNull
            context.Customers2.Add(
                new()
            {
                Name = "Foul Ole Ron"
            });

            context.Customers2.Add(
                new()
            {
                Name    = "Havelock Vetinari",
                Address = new()
            });

            #endregion

            context.SaveChanges();
        }

        Console.WriteLine();

        using (var context = new SomeDbContext())
        {
            var connection = context.Database.GetDbConnection();
            connection.Open();

            using var command   = connection.CreateCommand();
            command.CommandText = "SELECT Id, Name, Address_House, Address_Street, Address_City, Address_Postcode FROM Customers2";

            Console.WriteLine($"Id  Name               House   Street  City    Postcode");

            using var reader = command.ExecuteReader();
            while (reader.Read())
            {
                Console.Write($"{reader.GetInt32(0)}   {reader.GetString(1).PadRight(17)}  ");
                for (int i = 2; i <= 5; i++)
                {
                    Console.Write(reader.IsDBNull(i) ? "NULL    " : reader.GetString(i).PadRight(8));
                }
                Console.WriteLine();
            }

            connection.Close();
        }

        Console.WriteLine();
    }
Пример #9
0
    public static void Explicit_temporary_values_can_be_stored_in_entity_instance_2()
    {
        Console.WriteLine($">>>> Sample: {nameof(Explicit_temporary_values_can_be_stored_in_entity_instance_2)}");
        Console.WriteLine(">>>> Shows taking generated temporary values and setting them into entity instances.");
        Console.WriteLine();

        Helpers.RecreateCleanDatabase();

        using var context = new SomeDbContext();

        #region AddBlog
        var blog = new Blog();
        context.Add(blog);
        #endregion

        #region ShowValues
        Console.WriteLine($"Blog.Id value on entity instance = {blog.Id}");
        Console.WriteLine($"Blog.Id value tracked by EF = {context.Entry(blog).Property(e => e.Id).CurrentValue}");
        #endregion

        Console.WriteLine();

        #region ExplicitManipulation
        var post1 = new Post();
        var post2 = new Post();

        var blogIdEntry = context.Entry(blog).Property(e => e.Id);
        blog.Id = blogIdEntry.CurrentValue;
        blogIdEntry.IsTemporary = true;

        var post1IdEntry = context.Add(post1).Property(e => e.Id);
        post1.Id = post1IdEntry.CurrentValue;
        post1IdEntry.IsTemporary = true;
        post1.BlogId             = blog.Id;

        var post2IdEntry = context.Add(post2).Property(e => e.Id);
        post2.Id = post2IdEntry.CurrentValue;
        post2IdEntry.IsTemporary = true;
        post2.BlogId             = blog.Id;

        Console.WriteLine($"Blog has generated temporary ID = {blog.Id}");
        Console.WriteLine($"Post 1 has generated temporary ID = {post1.Id} and FK to Blog = {post1.BlogId}");
        Console.WriteLine($"Post 2 has generated temporary ID = {post2.Id} and FK to Blog = {post2.BlogId}");
        #endregion

        Console.WriteLine();
        Console.WriteLine("SavingChanges...");
        context.SaveChanges();
        Console.WriteLine();

        Console.WriteLine($"Blog has ID = {blog.Id}");
        Console.WriteLine($"Post 1 has ID = {post1.Id} and FK to Blog = {post1.BlogId}");
        Console.WriteLine($"Post 2 has ID = {post2.Id} and FK to Blog = {post2.BlogId}");

        Console.WriteLine();
    }
Пример #10
0
    public async Task Counts_when_execution_strategy_retries(bool async)
    {
        TotalExecutionStrategyOperationFailures = 0;

        for (var i = 1; i <= 3; i++)
        {
            using var context = new SomeDbContext();

            var executionCount        = 0;
            var executionStrategyMock = new ExecutionStrategyTest.TestExecutionStrategy(
                context,
                retryCount: 2,
                shouldRetryOn: e => e is ArgumentOutOfRangeException,
                getNextDelay: e => TimeSpan.FromTicks(0));

            if (async)
            {
                Assert.IsType <ArgumentOutOfRangeException>(
                    (await Assert.ThrowsAsync <RetryLimitExceededException>(
                         () =>
                         executionStrategyMock.ExecuteAsync(
                             () =>
                {
                    if (executionCount++ < 3)
                    {
                        throw new ArgumentOutOfRangeException();
                    }

                    Assert.True(false);
                    return(Task.FromResult(1));
                }))).InnerException);
            }
            else
            {
                Assert.IsType <ArgumentOutOfRangeException>(
                    Assert.Throws <RetryLimitExceededException>(
                        () =>
                        executionStrategyMock.Execute(
                            () =>
                {
                    if (executionCount++ < 3)
                    {
                        throw new ArgumentOutOfRangeException();
                    }

                    Assert.True(false);
                    return(0);
                })).InnerException);
            }

            Assert.Equal(3, executionCount);
            Assert.Equal(i * 3, TotalExecutionStrategyOperationFailures);
        }
    }
        public ImageController(IConfiguration configuration, IWebHostEnvironment environment, SomeDbContext context)
        {
            _configuration = configuration;
            _environment   = environment;

            _materialImages = new Dictionary <int, string>();
            _materialImages.Add(1, "/material/img_abc.jpg");
            _materialImages.Add(2, "/material/imgdasd.png");

            _context = context;
        }
    public static void Optional_dependents_with_a_required_property()
    {
        Console.WriteLine($">>>> Sample: {nameof(Optional_dependents_with_a_required_property)}");
        Console.WriteLine();

        Helpers.RecreateCleanDatabase();

        using (var context = new SomeDbContext())
        {
            #region NoAddress
            context.Customers1.Add(
                new()
            {
                Name = "Foul Ole Ron"
            });
            #endregion

            #region PostcodeOnly
            context.Customers1.Add(
                new()
            {
                Name    = "Havelock Vetinari",
                Address = new()
                {
                    Postcode = "AN1 1PL",
                }
            });
            #endregion

            context.SaveChanges();
        }

        using (var context = new SomeDbContext())
        {
            #region CheckForNullAddress
            foreach (var customer in context.Customers1)
            {
                Console.Write(customer.Name);

                if (customer.Address == null)
                {
                    Console.WriteLine(" has no address.");
                }
                else
                {
                    Console.WriteLine($" has postcode {customer.Address.Postcode}.");
                }
            }
            #endregion
        }

        Console.WriteLine();
    }
Пример #13
0
    public async Task Counts_when_query_is_executed(bool async)
    {
        TotalQueries = 0;

        for (var i = 1; i <= 3; i++)
        {
            using var context = new SomeDbContext();

            _ = async ? await context.Foos.ToListAsync() : context.Foos.ToList();

            Assert.Equal(i, TotalQueries);
        }
    }
Пример #14
0
        public static void CreateData(SomeDbContext _context)
        {
            //var users = Builder<Employee>.CreateListOfSize(1000)
            //    .All()
            //    .With(c => c.Id = 0)
            //    .With(c => c.Name = Name.First())
            //    .With(c => c.Surname = Name.Last())
            //    .Build();

            _context.Employees.Add(new Employee(EmployeeNames[0], 25));
            _context.Employees.Add(new Employee(EmployeeNames[1], 35));
            _context.SaveChanges();
        }
Пример #15
0
    public async Task Counts_when_SaveChanges_is_called(bool async)
    {
        TotalSaveChanges = 0;

        for (var i = 1; i <= 3; i++)
        {
            using var context = new SomeDbContext();

            context.Add(new Foo());

            _ = async ? await context.SaveChangesAsync() : context.SaveChanges();

            Assert.Equal(i, TotalSaveChanges);
        }
    }
Пример #16
0
        public async Task Counts_query_cache_hits_and_misses(bool async)
        {
            ResetCacheInfo();

            for (var i = 1; i <= 3; i++)
            {
                using var context = new SomeDbContext();

                var query = context.Foos.Where(e => e.Id == new Guid("6898CFFC-3DCC-45A6-A472-A23057462EE6"));

                _ = async ? await query.ToListAsync() : query.ToList();

                Assert.Equal(1, CompiledQueryCacheInfoMisses);
                Assert.Equal(i - 1, CompiledQueryCacheInfoHits);
            }
        }
    public static void Handling_nested_optional_dependents_sharing_table_with_principal()
    {
        Console.WriteLine($">>>> Sample: {nameof(Handling_nested_optional_dependents_sharing_table_with_principal)}");
        Console.WriteLine();

        Helpers.RecreateCleanDatabase();

        using (var context = new SomeDbContext())
        {
            var principal = new PrincipalWithNestedOptionalDependents()
            {
                DependentWithOptionalNestedDependents = new()
                {
                    Nested = new()
                }
            };

            context.Add(principal);

            Console.WriteLine("Saving principal with all non-null required dependent objects:");
            Console.WriteLine($"  Dependent with only optional properties is {(principal.DependentWithOptionalNestedDependents != null ? "not " : "")}null.");
            Console.WriteLine($"  Nested dependent with only optional properties is {(principal.DependentWithOptionalNestedDependents?.Nested != null ? "not " : "")}null.");


            Console.WriteLine();
            Console.WriteLine("SaveChanges will warn:");
            Console.WriteLine();
            context.SaveChanges();
            Console.WriteLine();
        }

        using (var context = new SomeDbContext())
        {
            var principal = context.PrincipalsWithNestedOptionalDependents.Single();
            Console.WriteLine("After querying back principal and dependents saved above:");
            Console.WriteLine($"  Dependent with only optional properties is {(principal.DependentWithOptionalNestedDependents != null ? "not " : "")}null.");
            Console.WriteLine($"  Nested dependent with only optional properties is {(principal.DependentWithOptionalNestedDependents?.Nested != null ? "not " : "")}null. <-- Note nested dependent is null here.");
        }

        Console.WriteLine();
    }
Пример #18
0
    public static void Explicit_temporary_values_can_be_stored_in_entity_instance_1()
    {
        Console.WriteLine($">>>> Sample: {nameof(Explicit_temporary_values_can_be_stored_in_entity_instance_1)}");
        Console.WriteLine(">>>> Shows using explicit temporary values with FK values to relate posts to a blog.");
        Console.WriteLine();

        Helpers.RecreateCleanDatabase();

        using var context = new SomeDbContext();

        #region MarkTemporary
        var blog = new Blog {
            Id = -1
        };
        var post1 = new Post {
            Id = -1, BlogId = -1
        };
        var post2 = new Post {
            Id = -2, BlogId = -1
        };

        context.Add(blog).Property(e => e.Id).IsTemporary  = true;
        context.Add(post1).Property(e => e.Id).IsTemporary = true;
        context.Add(post2).Property(e => e.Id).IsTemporary = true;

        Console.WriteLine($"Blog has explicit temporary ID = {blog.Id}");
        Console.WriteLine($"Post 1 has explicit temporary ID = {post1.Id} and FK to Blog = {post1.BlogId}");
        Console.WriteLine($"Post 2 has explicit temporary ID = {post2.Id} and FK to Blog = {post2.BlogId}");
        #endregion

        Console.WriteLine();
        Console.WriteLine("SavingChanges...");
        context.SaveChanges();
        Console.WriteLine();

        Console.WriteLine($"Blog has ID = {blog.Id}");
        Console.WriteLine($"Post 1 has ID = {post1.Id} and FK to Blog = {post1.BlogId}");
        Console.WriteLine($"Post 2 has ID = {post2.Id} and FK to Blog = {post2.BlogId}");

        Console.WriteLine();
    }
Пример #19
0
    public static void Backing_fields_with_trailing_underscores_are_matched()
    {
        Console.WriteLine($">>>> Sample: {nameof(Backing_fields_with_trailing_underscores_are_matched)}");
        Console.WriteLine();

        Helpers.RecreateCleanDatabase();

        using var context = new SomeDbContext();

        var userEntityType = context.Model.FindEntityType(typeof(User));

        var idProperty = userEntityType.FindProperty(nameof(User.Id));

        Console.WriteLine($"User entity detected backing field '{idProperty.FieldInfo.Name}' for property '{idProperty.Name}'");

        var nameProperty = userEntityType.FindProperty(nameof(User.Name));

        Console.WriteLine($"User entity detected backing field '{nameProperty.FieldInfo.Name}' for property '{nameProperty.Name}'");

        Console.WriteLine();
    }
 public MyController1(SomeDbContext context)
 {
     _context = context;
 }
 public UserFinder(SomeDbContext dbContext)
 {
     _dbContext = dbContext
 }
 public SomeService(ILogger <SomeService> logger, SomeDbContext context)
 {
     _logger  = logger;
     _context = context;
 }
 public static object GetContracts(Project project)
 {
     using (var myDbContext = new SomeDbContext())
     {
         myDbContext.DoSomething();
Пример #24
0
 public SomethingService(SomeDbContext context)
 {     // Init stuff.
 }
Пример #25
0
 public SomeQueryService(SomeDbContext context, IMapper mapper, ISieveProcessor sieveProcessor)
 {
     _context        = context;
     _mapper         = mapper;
     _sieveProcessor = sieveProcessor;
 }
 public SomeCommandRepository(SomeDbContext context, IUnitOfWork unitOfWork)
 {
     _context   = context;
     UnitOfWork = unitOfWork;
 }
 public DgmlController(SomeDbContext context)
 {
     _context = context;
 }