Beispiel #1
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);
        }
    }
Beispiel #2
0
 public ActionResult UploadFiles(int customerId)
 {
     if (Request.Files.Count == 0)
     {
         return(new HttpStatusCodeResult(HttpStatusCode.NotFound));
     }
     foreach (string file in Request.Files)
     {
         var    upload   = Request.Files[file];
         string filename = Guid.NewGuid().ToString() + Path.GetExtension(upload.FileName);
         // Save the file in FilesRoot/{CustomerId}/{GUID}
         string savePath = Path.Combine(FilesRoot, customerId.ToString());
         if (!Directory.Exists(savePath))
         {
             Directory.CreateDirectory(savePath);
         }
         upload.SaveAs(Path.Combine(savePath, filename));
         // Save file to database
         var fileUpload = new FileUploadModel()
         {
             CustomerId       = customerId,
             Filename         = filename,
             OriginalFilename = upload.FileName,
             ContentType      = upload.ContentType
         };
         db.FileUploads.Add(fileUpload);
         db.SaveChanges();
     }
     return(new HttpStatusCodeResult(HttpStatusCode.OK));
 }
    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();
    }
    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();
    }
Beispiel #5
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();
    }
    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();
    }
Beispiel #7
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();
        }
Beispiel #8
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);
        }
    }
    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();
    }
Beispiel #10
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();
    }