protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            RemoveVariableModelAnnotations(modelBuilder);

            modelBuilder.Entity <Patriarch>().HasData(
                new { Id = HierarchyId.GetRoot(), Name = "Eddard Stark" },
                new { Id = HierarchyId.Parse("/1/"), Name = "Robb Stark" },
                new { Id = HierarchyId.Parse("/2/"), Name = "Jon Snow" });

            modelBuilder.Entity <ConvertedPatriarch>(b =>
            {
                b.Property(e => e.HierarchyId)
                .HasConversion(v => HierarchyId.Parse(v), v => v.ToString());

                b.HasData(
                    new ConvertedPatriarch {
                    Id = 1, HierarchyId = HierarchyId.GetRoot().ToString(), Name = "Eddard Stark"
                },
                    new ConvertedPatriarch {
                    Id = 2, HierarchyId = HierarchyId.Parse("/1/").ToString(), Name = "Robb Stark"
                },
                    new ConvertedPatriarch {
                    Id = 3, HierarchyId = HierarchyId.Parse("/2/").ToString(), Name = "Jon Snow"
                });
            });
        }
Beispiel #2
0
        private void HierarchyIdIsPersistedCorrectlyLargerHierarchyTest()
        {
            ContextUtil.DbServer = DbServer.SQLServer;
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                context.BulkDelete(context.Categories.ToList());
            }

            var nodeIdAsString = "/1.1/-2/3/4/5/";

            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var entities = new List <Category> {
                    new Category
                    {
                        Name = "Deep Element",
                        HierarchyDescription = HierarchyId.Parse(nodeIdAsString)
                    }
                };
                context.BulkInsertOrUpdate(entities);
            }

            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var category = context.Categories.Single();
                Assert.Equal(nodeIdAsString, category.HierarchyDescription.ToString());
            }
        }
Beispiel #3
0
        public void Can_insert_HierarchyId()
        {
            using (_db.Database.BeginTransaction())
            {
                var entities = new List <Patriarch>
                {
                    new() { Id = HierarchyId.Parse("/2/1/"), Name = "Thrór" },
                    new() { Id = HierarchyId.Parse("/2/2/"), Name = "Thráin II" },
                    new() { Id = HierarchyId.Parse("/3/"), Name = "Thorin Oakenshield" }
                };

                _db.AddRange(entities);
                _db.SaveChanges();
                _db.ChangeTracker.Clear();

                var queried = _db.Patriarchy.Where(e => e.Name.StartsWith("Th")).OrderBy(e => e.Id).ToList();

                Assert.Equal(3, queried.Count);

                Assert.Equal(HierarchyId.Parse("/2/1/"), queried[0].Id);
                Assert.Equal("Thrór", queried[0].Name);

                Assert.Equal(HierarchyId.Parse("/2/2/"), queried[1].Id);
                Assert.Equal("Thráin II", queried[1].Name);

                Assert.Equal(HierarchyId.Parse("/3/"), queried[2].Id);
                Assert.Equal("Thorin Oakenshield", queried[2].Name);
            }
        }
Beispiel #4
0
        /// <summary>
        /// Возвращает путь для вставки в конец
        /// </summary>
        /// <param name="parentBlock"></param>
        /// <returns></returns>
        public HierarchyId GetAppendPath(Block parentBlock)
        {
            var index = context.Blocks.Count(x => x.Level == parentBlock.Level + 1 &&
                                             x.Path.IsDescendantOf(parentBlock.Path)) + 1;
            HierarchyId newItemPath = HierarchyId.Parse(parentBlock.Path + index.ToString() + "/");

            return(newItemPath);
        }
Beispiel #5
0
        public MappingProfile()
        {
            //from Domain to API Resource

            CreateMap <Category, CategoryResource>();

            CreateMap <Products, ProductResource>();


            //CreateMap<MyDbAcct, MyDBAcctsResources>();
            //CreateMap<MyDBAcctsResources, MyDbAcct>();


            CreateMap <MyDbAcct, MyDBAcctsResources>();
            CreateMap <MyDBAcctsResources, MyDbAcct>()
            .ForMember(a => a.acctId, opt => opt.Ignore());



            CreateMap <string, HierarchyId>().ConvertUsing(s => HierarchyId.Parse(s));


            CreateMap <Purchase, SavePurchaseResource>();
            CreateMap <SavePurchaseResource, Purchase>()
            .ForMember(p => p.purchId, opt => opt.Ignore()); //ignor mapping this field

            CreateMap <Purchase, PurchaseResource>()
            .ForMember(pr => pr.purchaseItems, opt => opt.MapFrom(p => p.purchaseItems));
            //.ForMember(dest => dest.dbAcct,opt => opt.MapFrom(src => src.dbAcct));
            //.ForMember(pr=>pr.purchaseItems,opt=>opt.MapFrom(p=>p.purchaseItems.Select(pr=> pr.Products)));

            //.ForPath(dest => dest.purchase,opt => opt.MapFrom(src => src.dbAcct.Purchases))
            //.ForMember(pr=>pr.product,op=>opt.MapFrom(p=>p.purchaseItems))

            //.ForMember(pr=>pr.Products,opt=>opt.MapFrom(p=> new ProductResource {prodName = "Hello" }))
            //.ForMember(dest => dest.Products.prodName,opt => opt.UseValue<string>("Hello"));

            //.ForMember(pr=>pr.product,opt=>opt.MapFrom(p=>p.purchaseItems.Select(pr=> new ProductResource{prodId = pr.prodId})));
            //.AfterMap((p,pr)=> Mapper.Map(p.purchaseItems,pr.Products));

            CreateMap <Purchase, PurchaseResource>();
            CreateMap <PurchaseResource, Purchase>();


            CreateMap <PurchaseItems, PurchaseItemsResource>();
            CreateMap <PurchaseItemsResource, PurchaseItems>();

            //from API Resource(source) to Domain
            //CreateMap<PurchaseResource, Purchase>()
            //    .ForMember(p=>p.purchaseItems,opt=>opt.MapFrom(pr=>pr.purchaseItems.Select(id=>new PurchaseItems {purchId = id})));

            CreateMap <PurchaseQuereyResource, PurchaseQuery>();
            CreateMap <PurchaseQuery, PurchaseQuereyResource>();



            //CreateMap<PurchaseItemsResource, PurchaseItems>();
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            RemoveVariableModelAnnotations(modelBuilder);

            modelBuilder.Entity <Patriarch>().HasData(
                new { Id = HierarchyId.GetRoot(), Name = "Eddard Stark" },
                new { Id = HierarchyId.Parse("/1/"), Name = "Robb Stark" },
                new { Id = HierarchyId.Parse("/2/"), Name = "Jon Snow" });
        }
        public void Should_GetEphraimEntryById()
        {
            // Arrange
            var databaseContext = new AbrahamicContext();

            // Act
            databaseContext.Database.EnsureCreated();
            var ephraim = databaseContext.Patriarchy.Single(w => w.Id == HierarchyId.Parse("/1/1/11.1/"));

            // Assert
            Assert.Equal("Ephraim", ephraim.Name);
        }
Beispiel #8
0
        public void GetDescendent_can_translate()
        {
            var results = Enumerable.ToList(
                from p in _db.Patriarchy
                where p.Id.GetLevel() == 0
                select p.Id.GetDescendant(null, null));

            Assert.Equal(
                condense(@"SELECT [p].[Id].GetDescendant(NULL, NULL) FROM [Patriarchy] AS [p] WHERE [p].[Id].GetLevel() = CAST(0 AS smallint)"),
                condense(_db.Sql));

            Assert.Equal(new[] { HierarchyId.Parse("/1/") }, results);
        }
Beispiel #9
0
        public void Converted_HierarchyId_can_be_sent_as_parameter()
        {
            var results = Enumerable.ToList(
                from p in _db.ConvertedPatriarchy
                where p.HierarchyId == HierarchyId.Parse("/1/").ToString()
                select p.Name);

            Assert.Equal(
                condense(@"SELECT [c].[Name] FROM [ConvertedPatriarchy] AS [c] WHERE [c].[HierarchyId] = '/1/'"),
                condense(_db.Sql));

            Assert.Equal(new[] { "Isaac" }, results);
        }
Beispiel #10
0
        public void Parse_can_translate()
        {
            var results = Enumerable.ToList(
                from p in _db.Patriarchy
                where p.Id == HierarchyId.GetRoot()
                select HierarchyId.Parse(p.Id.ToString()));

            Assert.Equal(
                condense(@"SELECT hierarchyid::Parse([p].[Id].ToString()) FROM [Patriarchy] AS [p] WHERE [p].[Id] = '/'"),
                condense(_db.Sql));

            Assert.Equal(new[] { HierarchyId.Parse("/") }, results);
        }
Beispiel #11
0
 protected override void OnModelCreating(ModelBuilder modelBuilder)
 => modelBuilder.Entity <Patriarch>()
 .HasData(
     new Patriarch {
     Id = HierarchyId.GetRoot(), Name = "Abraham"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/"), Name = "Isaac"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/"), Name = "Jacob"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/1/"), Name = "Reuben"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/2/"), Name = "Simeon"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/3/"), Name = "Levi"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/4/"), Name = "Judah"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/5/"), Name = "Issachar"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/6/"), Name = "Zebulun"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/7/"), Name = "Dan"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/8/"), Name = "Naphtali"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/9/"), Name = "Gad"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/10/"), Name = "Asher"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/11.1/"), Name = "Ephraim"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/11.2/"), Name = "Manasseh"
 },
     new Patriarch {
     Id = HierarchyId.Parse("/1/1/12/"), Name = "Benjamin"
 });
        private void DbQuery_with_TVFs_mapped_to_arbitrary_instance_methods_involving_hierarchyid_types_works(
            Func <IQueryable <IQueryable <SupplierWithHierarchyId> >, List <IQueryable <SupplierWithHierarchyId> > > toList)
        {
            using (var context = new HierarchyIdNorthwindContext(_connectionString))
            {
                var suppliers = (from x in context.Suppliers
                                 select
                                 ArbitrarySuppliersWithinRange(
                                     HierarchyId.Parse("/1/"),
                                     HierarchyId.Parse("/10/"))).ToList();

                Assert.Equal(16, suppliers.Count);
            }
        }
        public async Task <IActionResult> CreateDbAccounts(MyDBAcctsResources acctsResource)

        {
            //throw new Exception();

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //acctsResource.nodePath = HierarchyId.Parse(acctsResource.path);

            HierarchyId parentItem = HierarchyId.Parse(acctsResource.nodePath);

            //var parent = context.myDbAccts.FirstOrDefault(e => e.nodePath == HierarchyId.Parse(acctsResource.nodePath).GetAncestor(1));

            var lastItemInCurrentLevel = context.myDbAccts.Where(x => x.nodePath.GetAncestor(1) == parentItem)
                                         .OrderByDescending(x => x.nodePath)
                                         .FirstOrDefault();

            var child1Node = lastItemInCurrentLevel != null ? lastItemInCurrentLevel.nodePath : null;

            var newNode = parentItem.GetDescendant(child1Node, null);

            acctsResource.nodePath = newNode.ToString();

            var acct = mapper.Map <MyDBAcctsResources, MyDbAcct>(acctsResource);



            context.myDbAccts.Add(acct);

            //foreach (var item in purchaseResource.purchaseItems)
            //{
            //    context.purchaseItems.Add(item);

            //}


            await context.SaveChangesAsync();



            var result = mapper.Map <MyDbAcct, MyDBAcctsResources>(acct);



            return(Ok(result));
        }
Beispiel #14
0
        public void HierarchyId_can_call_method_on_parameter()
        {
            var isaac = HierarchyId.Parse("/1/");

            var results = Enumerable.ToList(
                from p in _db.Patriarchy
                where isaac.IsDescendantOf(p.Id)
                select p.Name);

            Assert.Equal(
                condense(@"SELECT [p].[Name] FROM [Patriarchy] AS [p] WHERE @__isaac_0.IsDescendantOf([p].[Id]) = CAST(1 AS bit)"),
                condense(_db.Sql));

            Assert.Equal(new[] { "Abraham", "Isaac" }, results);
        }
Beispiel #15
0
                private static Dictionary <MethodInfo, string> GetRenamedMethodFunctions()
                {
                    var result = new Dictionary <MethodInfo, string>();

                    result.Add(GetStaticMethod(() => HierarchyId.GetRoot()), "HierarchyIdGetRoot");
                    result.Add(GetStaticMethod(() => HierarchyId.Parse(default(string))), "HierarchyIdParse");
                    result.Add(GetInstanceMethod((HierarchyId h) => h.GetAncestor(default(int))), "GetAncestor");
                    result.Add(
                        GetInstanceMethod((HierarchyId h) => h.GetDescendant(default(HierarchyId), default(HierarchyId))), "GetDescendant");
                    result.Add(GetInstanceMethod((HierarchyId h) => h.GetLevel()), "GetLevel");
                    result.Add(GetInstanceMethod((HierarchyId h) => h.IsDescendantOf(default(HierarchyId))), "IsDescendantOf");
                    result.Add(
                        GetInstanceMethod((HierarchyId h) => h.GetReparentedValue(default(HierarchyId), default(HierarchyId))),
                        "GetReparentedValue");
                    return(result);
                }
Beispiel #16
0
                private static IEnumerable <MethodInfo> GetSupportedMethods()
                {
                    yield return(GetStaticMethod(() => HierarchyId.GetRoot()));

                    yield return(GetStaticMethod(() => HierarchyId.Parse(default(string))));

                    yield return(GetInstanceMethod((HierarchyId h) => h.GetAncestor(default(int))));

                    yield return(GetInstanceMethod((HierarchyId h) => h.GetDescendant(default(HierarchyId), default(HierarchyId))));

                    yield return(GetInstanceMethod((HierarchyId h) => h.GetLevel()));

                    yield return(GetInstanceMethod((HierarchyId h) => h.IsDescendantOf(default(HierarchyId))));

                    yield return(GetInstanceMethod((HierarchyId h) => h.GetReparentedValue(default(HierarchyId), default(HierarchyId))));
                }
        public void DbQuery_SelectMany_with_TVFs_and_hierarchyid_types_works()
        {
            using (var context = new HierarchyIdNorthwindContext(_connectionString))
            {
                var results =
                    (from s1 in
                     context.SuppliersWithinRange(HierarchyId.Parse("/-100/"), HierarchyId.Parse("/100/"))
                     from s2 in
                     context.SuppliersWithinRange(HierarchyId.Parse("/-100/"), HierarchyId.Parse("/100/"))
                     where s1.Name == s2.Name
                     select new
                {
                    s1,
                    s2
                }).ToList();


                Assert.Equal(16, results.Count);
            }
        }
Beispiel #18
0
        private void Dive(TreeItem currentNode, HierarchyId currentPath)
        {
            var newBlock = new Block
            {
                Id            = Guid.NewGuid(),
                Path          = currentPath,
                Level         = currentPath.GetLevel(),
                BlockName     = currentNode.Name,
                IsChoice      = currentNode.IsChoice,
                Order         = currentNode.Order,
                AttributeList = new Collection <AttributeMetadata>()
            };
            var subBlocks = currentNode.SubItems.Where(x => x.SubItems != null).ToArray();

            //блок
            for (int i = 1; i <= subBlocks.Length; i++)
            {
                var subItem = currentNode.SubItems[i - 1];
                Dive(subItem, HierarchyId.Parse(currentPath + i.ToString() + "/"));
            }

            /*var subAttributes = currentNode.SubItems.Where(x => x.SubItems == null).Select(x => new AttributeMetadata
             *  {
             *      Id = Guid.NewGuid(),
             *      AttributeName = x.Name,
             *      BlockId = newBlock.Id,
             *      Placeholder = x.Placeholder,
             *  });*/
            foreach (var node in currentNode.SubItems.Where(x => x.SubItems == null))
            {
                newBlock.AttributeList.Add(new AttributeMetadata
                {
                    Id            = Guid.NewGuid(),
                    AttributeName = node.Name,
                    Placeholder   = node.Placeholder,
                    Order         = node.Order
                });
            }
            context.Blocks.Add(newBlock);
        }
Beispiel #19
0
        private void HierarchyIdColumnTest()
        {
            ContextUtil.DbServer = DbServer.SQLServer;
            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                context.BulkDelete(context.Categories.ToList());
            }

            using (var context = new TestContext(ContextUtil.GetOptions()))
            {
                var nodeIdAsString = "/1/";
                var entities       = new List <Category> {
                    new Category
                    {
                        Name = "Root Element",
                        HierarchyDescription = HierarchyId.Parse(nodeIdAsString)
                    }
                };

                context.BulkInsertOrUpdate(entities);
            }
        }
Beispiel #20
0
        public void Configure(EntityTypeBuilder <Employee> builder)
        {
            builder.HasKey(opt => opt.Id);
            builder.Property(opt => opt.Id)
            .ValueGeneratedOnAdd();

            builder.Property(opt => opt.Name)
            .HasMaxLength(100)
            .IsRequired();

            builder.Property(opt => opt.HierarchyId)
            .IsRequired();
            builder.HasIndex(opt => opt.HierarchyId)
            .IsUnique();

            builder.HasData(new Employee[]
            {
                new Employee {
                    Id = 1, Name = "Lidia Brewer", HierarchyId = HierarchyId.Parse("/1/")
                },
                new Employee {
                    Id = 2, Name = "Hannah Wicks", HierarchyId = HierarchyId.Parse("/2/")
                },
                new Employee {
                    Id = 3, Name = "Sheridan Perkins", HierarchyId = HierarchyId.Parse("/1/1/")
                },
                new Employee {
                    Id = 4, Name = "Zakaria Bailey", HierarchyId = HierarchyId.Parse("/1/2/")
                },
                new Employee {
                    Id = 5, Name = "Albert Woodward", HierarchyId = HierarchyId.Parse("/1/2/1/")
                },
                new Employee {
                    Id = 6, Name = "Arron Mcdaniel", HierarchyId = HierarchyId.Parse("/1/2/2/")
                }
            });

            builder.ToTable(nameof(Employee));
        }
        public void DbQuery_SelectMany_with_TVFs_and_hierarchyid_types_using_Point_and_Point_return_in_function_import_works()
        {
            using (var context = new HierarchyIdNorthwindContext(_connectionString))
            {
                context.Database.Initialize(force: false);

                var results =
                    (from s1 in
                     context.SupplierHierarchyIdsWithinRange(
                         HierarchyId.Parse("/-100/"),
                         HierarchyId.Parse("/100/"))
                     from s2 in
                     context.SupplierHierarchyIdsWithinRange(
                         HierarchyId.Parse("/-100/"),
                         HierarchyId.Parse("/100/"))
                     select new
                {
                    s1,
                    s2
                }).ToList();

                Assert.Equal(256, results.Count);
            }
        }
Beispiel #22
0
        protected override void Seed(HierarchyIdNorthwindContext context)
        {
            context.Database.ExecuteSqlCommand(
                @"

                CREATE FUNCTION [dbo].[fx_SuppliersWithinRange]
                (	
	                @path1 hierarchyid, 
	                @path2 hierarchyid
                )
                RETURNS TABLE 
                AS
                RETURN 
                (
	                SELECT [Id],[Name],[Path]
	                FROM [ProductivityApiTests.HierarchyIdNorthwindContext].[dbo].[SupplierWithHierarchyIds] as supplier
	                Where supplier.Path > @path1 AND supplier.Path < @path2
                )"
                );

            context.Database.ExecuteSqlCommand(
                @"

                CREATE FUNCTION [dbo].[fx_SupplierHierarchyIdsWithinRange]
                (	
	                @path1 hierarchyid, 
	                @path2 hierarchyid
                )
                RETURNS TABLE 
                AS
                RETURN 
                (
	                SELECT [Path]
	                FROM [ProductivityApiTests.HierarchyIdNorthwindContext].[dbo].[SupplierWithHierarchyIds] as supplier
	                Where supplier.Path > @path1 AND supplier.Path < @path2
                )"
                );

            new List <SupplierWithHierarchyId>
            {
                new SupplierWithHierarchyId
                {
                    Name = "Supplier1",
                    Path = HierarchyId.Parse("/1/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier2",
                    Path = HierarchyId.Parse("/1/1/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier3",
                    Path = HierarchyId.Parse("/1/1.1/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier4",
                    Path = HierarchyId.Parse("/1/2/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier5",
                    Path = HierarchyId.Parse("/1/1.1/2/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier6",
                    Path = HierarchyId.Parse("/1/3/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier7",
                    Path = HierarchyId.Parse("/1/4/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier8",
                    Path = HierarchyId.Parse("/1/4/1/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier9",
                    Path = HierarchyId.Parse("/2/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier10",
                    Path = HierarchyId.Parse("/3/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier11",
                    Path = HierarchyId.Parse("/3/1/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier12",
                    Path = HierarchyId.Parse("/3/2/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier13",
                    Path = HierarchyId.Parse("/3/2.1/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier14",
                    Path = HierarchyId.Parse("/3/2.1/3/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier15",
                    Path = HierarchyId.Parse("/4/")
                },
                new SupplierWithHierarchyId
                {
                    Name = "Supplier16",
                    Path = HierarchyId.Parse("/5/")
                },
            }.ForEach(s => context.Suppliers.Add(s));

            new List <WidgetWithHierarchyId>
            {
                new WidgetWithHierarchyId
                {
                    Name            = "Widget1",
                    SomeHierarchyId = HierarchyId.Parse("/11/"),
                    Complex         = new ComplexWithHierarchyId
                    {
                        NotHierarchyId      = "1",
                        SomeMoreHierarchyId = HierarchyId.Parse("/11/1/")
                    }
                },
                new WidgetWithHierarchyId
                {
                    Name            = "Widget2",
                    SomeHierarchyId = HierarchyId.Parse("/12/"),
                    Complex         = new ComplexWithHierarchyId
                    {
                        NotHierarchyId      = "1",
                        SomeMoreHierarchyId = HierarchyId.Parse("/12/1/")
                    }
                },
                new WidgetWithHierarchyId
                {
                    Name            = "Widget3",
                    SomeHierarchyId = HierarchyId.Parse("/13/"),
                    Complex         = new ComplexWithHierarchyId
                    {
                        NotHierarchyId      = "1",
                        SomeMoreHierarchyId = HierarchyId.Parse("/13/1/")
                    }
                },
                new WidgetWithHierarchyId
                {
                    Name            = "Widget4",
                    SomeHierarchyId = HierarchyId.Parse("/14/"),
                    Complex         = new ComplexWithHierarchyId
                    {
                        NotHierarchyId      = "1",
                        SomeMoreHierarchyId = HierarchyId.Parse("/14/1/")
                    }
                },
            }.ForEach(w => context.Widgets.Add(w));
        }
Beispiel #23
0
        public async Task <List <DetailInTreeView> > AddChildDetailAsync(
            int parentDetailId,
            string childDetailName,
            int countToAdd)
        {
            var detailsIdsForbiddenToAdd = new List <int>
            {
                parentDetailId
            };

            var resultListOfDetails = new List <DetailInTreeView>();

            await using (var transaction = await _context.Database.BeginTransactionAsync())
            {
                var retrievedDetail =
                    await _context.Details
                    .AsNoTracking()
                    .SingleOrDefaultAsync(x => x.Name == childDetailName)
                    .ConfigureAwait(false);


                var parentHierarchyIds = await GetDetailHierarchyIdsAsync(parentDetailId);

                // Handle case when there is already a detail with such name in db
                if (retrievedDetail != null)
                {
                    var ancestorsLevels = new List <HierarchyId>();

                    parentHierarchyIds.ForEach(x =>
                    {
                        var selectedNodeLevel = x.GetLevel();

                        for (var i = 1; i < selectedNodeLevel; i++)
                        {
                            ancestorsLevels.Add(x.GetAncestor(i));
                        }
                    });

                    var retrievedForbiddenIds = await _context.DetailRelations
                                                .AsNoTracking()
                                                .Where(x => ancestorsLevels.Contains(x.HierarchyId))
                                                .Select(x => x.DetailId)
                                                .ToListAsync()
                                                .ConfigureAwait(false);

                    detailsIdsForbiddenToAdd.AddRange(retrievedForbiddenIds);

                    var existedDetailRelation = await _context.DetailRelations
                                                .AsNoTracking()
                                                .FirstOrDefaultAsync(x => x.DetailId == retrievedDetail.DetailId)
                                                .ConfigureAwait(false);

                    var existedChildRelations = await _context.DetailRelations
                                                .AsNoTracking()
                                                .Where(x => x.HierarchyId.IsDescendantOf(existedDetailRelation.HierarchyId))
                                                .ToListAsync()
                                                .ConfigureAwait(false);


                    existedChildRelations.ForEach(x =>
                    {
                        if (detailsIdsForbiddenToAdd.Contains(x.DetailId))
                        {
                            var exceptionMessage = "You can\'t add the detail!" +
                                                   "\n\rRecursive dependency" +
                                                   "\n\ris not allowed.";

                            throw new BusinessLogicException(exceptionMessage);
                        }
                    });

                    var childHierarchyIds = await _context.DetailRelations
                                            .AsNoTracking()
                                            .Where(x => parentHierarchyIds
                                                   .Contains(x.HierarchyId.GetAncestor(1)))
                                            .Select(x => x.HierarchyId)
                                            .ToListAsync()
                                            .ConfigureAwait(false);


                    var hierarchyIdsToAdd = new List <HierarchyId>();

                    parentHierarchyIds.ForEach(x =>
                    {
                        var hierarchyIdToAdd = HierarchyId.Parse(
                            x.ToString() +
                            $"{retrievedDetail.DetailId}/");

                        hierarchyIdsToAdd.Add(hierarchyIdToAdd);
                    });


                    // Handle case when detail is already present in the selected scope
                    if (childHierarchyIds != null)
                    {
                        var relationsToUpdate =
                            await _context.DetailRelations
                            .Where(x =>
                                   hierarchyIdsToAdd.Contains(x.HierarchyId))
                            .ToListAsync()
                            .ConfigureAwait(false);

                        if (relationsToUpdate.Any())
                        {
                            relationsToUpdate.ForEach(x =>
                            {
                                x.Count += countToAdd;

                                resultListOfDetails.Add(new DetailInTreeView
                                {
                                    DetailId       = x.DetailId,
                                    Name           = childDetailName,
                                    Count          = x.Count,
                                    HierarchyLevel = x.HierarchyId
                                });
                            });

                            await _context.SaveChangesAsync().ConfigureAwait(false);

                            await transaction.CommitAsync().ConfigureAwait(false);

                            return(resultListOfDetails);
                        }
                    }

                    // Handle case when detail is NOT present in the selected scope
                    var parentHierarchyIdToChange = existedDetailRelation.HierarchyId.GetAncestor(1);

                    var childRelationsToAdd = new List <DetailRelation>();

                    existedChildRelations.ForEach(x =>
                    {
                        parentHierarchyIds.ForEach(y =>
                        {
                            childRelationsToAdd
                            .Add(
                                new DetailRelation
                            {
                                DetailId    = x.DetailId,
                                HierarchyId = x.HierarchyId
                                              .GetReparentedValue(parentHierarchyIdToChange, y),
                                Count = x.DetailId == retrievedDetail.DetailId ? countToAdd : x.Count
                            });
                        });
                    });

                    _context.DetailRelations
                    .AddRange(childRelationsToAdd);

                    await _context.SaveChangesAsync().ConfigureAwait(false);

                    var hierarchyIdsOfAddedRelations =
                        childRelationsToAdd.Select(x => x.HierarchyId);

                    resultListOfDetails = await _context.DetailRelations
                                          .AsNoTracking()
                                          .Include(x => x.Detail)
                                          .Where(x => hierarchyIdsOfAddedRelations.Contains(x.HierarchyId))
                                          .Select(x => new DetailInTreeView
                    {
                        DetailId       = x.DetailId,
                        Name           = x.Detail.Name,
                        Count          = x.Count,
                        HierarchyLevel = x.HierarchyId
                    })
                                          .ToListAsync()
                                          .ConfigureAwait(false);

                    await transaction.CommitAsync().ConfigureAwait(false);

                    return(resultListOfDetails);
                }

                // Handle case when there is no detail with such name in db
                if (retrievedDetail == null)
                {
                    var addedDetail = _context.Details.Add(
                        new Detail
                    {
                        Name = childDetailName
                    });

                    await _context.SaveChangesAsync().ConfigureAwait(false);

                    var parentDetailRelations = await _context.DetailRelations
                                                .AsNoTracking()
                                                .Where(x => x.DetailId == parentDetailId)
                                                .ToListAsync()
                                                .ConfigureAwait(false);

                    var relationsToAdd = new List <DetailRelation>();

                    parentDetailRelations.ForEach(x =>
                    {
                        var hierarchyIdToAdd = HierarchyId.Parse(
                            x.HierarchyId.ToString() + $"{addedDetail.Entity.DetailId}/");

                        var relationToAdd = new DetailRelation
                        {
                            DetailId    = addedDetail.Entity.DetailId,
                            Count       = countToAdd,
                            HierarchyId = hierarchyIdToAdd
                        };

                        relationsToAdd.Add(relationToAdd);
                    });

                    _context.AddRange(relationsToAdd);

                    await _context.SaveChangesAsync().ConfigureAwait(false);

                    relationsToAdd.ForEach(x =>
                    {
                        resultListOfDetails.Add(new DetailInTreeView
                        {
                            DetailId       = x.DetailId,
                            Name           = addedDetail.Entity.Name,
                            Count          = x.Count,
                            HierarchyLevel = x.HierarchyId
                        });
                    });
                }

                await transaction.CommitAsync().ConfigureAwait(false);
            }

            return(resultListOfDetails);
        }
Beispiel #24
0
 public void GetAncestor_returns_null_when_too_high()
 => Assert.Null(HierarchyId.Parse("/1/").GetAncestor(2));
Beispiel #25
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity <Patriarch>()
            .HasData(
                new Patriarch {
                Id = HierarchyId.GetRoot(), Name = "Abraham"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/"), Name = "Isaac"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/"), Name = "Jacob"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/1/"), Name = "Reuben"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/2/"), Name = "Simeon"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/3/"), Name = "Levi"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/4/"), Name = "Judah"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/5/"), Name = "Issachar"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/6/"), Name = "Zebulun"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/7/"), Name = "Dan"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/8/"), Name = "Naphtali"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/9/"), Name = "Gad"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/10/"), Name = "Asher"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/11.1/"), Name = "Ephraim"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/11.2/"), Name = "Manasseh"
            },
                new Patriarch {
                Id = HierarchyId.Parse("/1/1/12/"), Name = "Benjamin"
            });

            modelBuilder.Entity <ConvertedPatriarch>(b =>
            {
                b.Property(e => e.HierarchyId)
                .HasConversion(v => HierarchyId.Parse(v), v => v.ToString());

                b.HasData(
                    new ConvertedPatriarch {
                    Id = 1, HierarchyId = HierarchyId.GetRoot().ToString(), Name = "Abraham"
                },
                    new ConvertedPatriarch {
                    Id = 2, HierarchyId = HierarchyId.Parse("/1/").ToString(), Name = "Isaac"
                },
                    new ConvertedPatriarch {
                    Id = 3, HierarchyId = HierarchyId.Parse("/1/1/").ToString(), Name = "Jacob"
                },
                    new ConvertedPatriarch {
                    Id = 4, HierarchyId = HierarchyId.Parse("/1/1/1/").ToString(), Name = "Reuben"
                },
                    new ConvertedPatriarch {
                    Id = 5, HierarchyId = HierarchyId.Parse("/1/1/2/").ToString(), Name = "Simeon"
                },
                    new ConvertedPatriarch {
                    Id = 6, HierarchyId = HierarchyId.Parse("/1/1/3/").ToString(), Name = "Levi"
                },
                    new ConvertedPatriarch {
                    Id = 7, HierarchyId = HierarchyId.Parse("/1/1/4/").ToString(), Name = "Judah"
                },
                    new ConvertedPatriarch {
                    Id = 8, HierarchyId = HierarchyId.Parse("/1/1/5/").ToString(), Name = "Issachar"
                },
                    new ConvertedPatriarch {
                    Id = 9, HierarchyId = HierarchyId.Parse("/1/1/6/").ToString(), Name = "Zebulun"
                },
                    new ConvertedPatriarch {
                    Id = 10, HierarchyId = HierarchyId.Parse("/1/1/7/").ToString(), Name = "Dan"
                },
                    new ConvertedPatriarch {
                    Id = 11, HierarchyId = HierarchyId.Parse("/1/1/8/").ToString(), Name = "Naphtali"
                },
                    new ConvertedPatriarch {
                    Id = 12, HierarchyId = HierarchyId.Parse("/1/1/9/").ToString(), Name = "Gad"
                },
                    new ConvertedPatriarch {
                    Id = 13, HierarchyId = HierarchyId.Parse("/1/1/10/").ToString(), Name = "Asher"
                },
                    new ConvertedPatriarch {
                    Id = 14, HierarchyId = HierarchyId.Parse("/1/1/11.1/").ToString(), Name = "Ephraim"
                },
                    new ConvertedPatriarch {
                    Id = 15, HierarchyId = HierarchyId.Parse("/1/1/11.2/").ToString(), Name = "Manasseh"
                },
                    new ConvertedPatriarch {
                    Id = 16, HierarchyId = HierarchyId.Parse("/1/1/12/").ToString(), Name = "Benjamin"
                });
            });
        }
Beispiel #26
0
        public async Task <IActionResult> AddNewInstance([FromBody] AddEmployeeDto newInstance)

        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (newInstance.ParentId.HasValue) //dodavanje postojecem nodu u stablu
            {
                //dohvati roditelja nove instance
                Employee parent = await _context.Employees.FindAsync(newInstance.ParentId.Value);

                if (parent is null) //roditelj ne postoji
                {
                    return(NotFound());
                }

                //dohvati zadnje dodano dijete danog roditelja
                var lastAddedItemOfParent = await _context.Employees
                                            .Where(x => x.HierarchyId.GetAncestor(1) == parent.HierarchyId)
                                            .OrderByDescending(x => x.HierarchyId)
                                            .FirstOrDefaultAsync();

                //kreiraj novu instancu koristenjem HierarchyId roditelja i zadnjeg djeteta (ako postoji)
                var newInstnace = new Employee
                {
                    Name = newInstance.Name,

                    //Treba poceti sa HierarchyId roditelja i treba biti veci od zadnjeg djeteta
                    //tipa ako roditelj pocinje sa 3, a zadnje dodano dijete je 3/1, onda ce novo dijete imati 3/2
                    HierarchyId = parent.HierarchyId.GetDescendant(lastAddedItemOfParent?.HierarchyId ?? null, null)
                };

                //dodaj u kolekciju i spremi u bazu
                _context.Employees.Add(newInstnace);

                await _context.SaveChangesAsync();

                //NewChild treba imati veci HierarchyId od LastAddedChild u slucaju da je LastAddedChild != null
                //Ako je LastAddedChild null znaci da je dodano prvo dijete za danog roditelja
                return(Ok(new
                {
                    LastAddedChild = (lastAddedItemOfParent != null) ? new EmployeeDto
                    {
                        Id = lastAddedItemOfParent.Id,
                        Hierarchy = lastAddedItemOfParent.HierarchyId.ToString(),
                        Level = lastAddedItemOfParent.HierarchyId.GetLevel(),
                        Name = lastAddedItemOfParent.Name
                    } : null,
                    NewChild = new EmployeeDto
                    {
                        Id = newInstnace.Id,
                        Hierarchy = newInstnace.HierarchyId.ToString(),
                        Level = newInstnace.HierarchyId.GetLevel(),
                        Name = newInstnace.Name
                    }
                }));
            }
            else
            {
                //dohvati zadnje dodano dijete na prvoj razini
                var lastItemInCurrentLevel = _context.Employees
                                             .Where(x => x.HierarchyId.GetLevel() == 1)
                                             .OrderByDescending(x => x.HierarchyId)
                                             .FirstOrDefault();

                if (lastItemInCurrentLevel is null) //dodajemo prvi root element
                {
                    var newInstnace = new Employee
                    {
                        Name        = newInstance.Name,
                        HierarchyId = HierarchyId.Parse("/1/")
                    };

                    _context.Employees.Add(newInstnace);

                    await _context.SaveChangesAsync();

                    return(Ok(new EmployeeDto
                    {
                        Id = newInstnace.Id,
                        Hierarchy = newInstnace.HierarchyId.ToString(),
                        Level = newInstnace.HierarchyId.GetLevel(),
                        Name = newInstnace.Name
                    }));
                }

                //DRUGI SOLUTION
                //Kao root moguce je koristiti primary key novog dodanog elementa (losa praksa)
                //Tipa ako je primary key 10 onda ce HierarchyId biti /10/ i brojevi nece ici redom


                //postoji vec root element i dodajemo novog
                //nije ni ovo dobro rjesenje. Ako dode do dva zahtjeva u isto vrijeme jedan ce proci a jedan nece

                var nextHierarchyId = lastItemInCurrentLevel.HierarchyId.GetNextRootId();

                var newInstnace2 = new Employee
                {
                    Name        = newInstance.Name,
                    HierarchyId = HierarchyId.Parse($"/{nextHierarchyId}/")
                };

                _context.Employees.Add(newInstnace2);

                await _context.SaveChangesAsync();

                return(Ok(new EmployeeDto
                {
                    Id = newInstnace2.Id,
                    Hierarchy = newInstnace2.HierarchyId.ToString(),
                    Level = newInstnace2.HierarchyId.GetLevel(),
                    Name = newInstnace2.Name
                }));
            }
        }
Beispiel #27
0
        private async Task AddChildDetailAsync(TreeNode selectedNode)
        {
            using (var addChildDetailForm = new AddChildForm(_formsHelper))
            {
                if (addChildDetailForm.ShowDialog() == DialogResult.OK)
                {
                    List <DetailInTreeView> addedChildDetails = null;

                    try
                    {
                        addedChildDetails = await _detailService.AddChildDetailAsync(
                            SelectedNodeTag.DetailId,
                            addChildDetailForm.EnteredName,
                            addChildDetailForm.CountToAdd);
                    }
                    catch (BusinessLogicException e)
                    {
                        ShowMessageDialog(e.Message);

                        return;
                    }

                    var addedDetailId =
                        addedChildDetails
                        .FirstOrDefault(x => x.Name == addChildDetailForm.EnteredName).DetailId;

                    var detailHierarchyIds = await _detailService
                                             .GetDetailHierarchyIdsAsync(SelectedNodeTag.DetailId);

                    // Handle case when detail is already present in the selected scope
                    var detailNodes = new List <TreeNode>();

                    detailHierarchyIds.ForEach(detailHierarchyId =>
                    {
                        var detailNode = treeView.Nodes
                                         .Find(detailHierarchyId.ToString(), true)
                                         .SingleOrDefault();

                        if (detailNode != null)
                        {
                            detailNodes.Add(detailNode);
                        }
                    });

                    detailNodes.ForEach(detailNode =>
                    {
                        var detailNodeTag = detailNode.Tag as DetailInTreeView;

                        var targetNodeHierarchyId = HierarchyId
                                                    .Parse($"{detailNodeTag.HierarchyLevel}{addedDetailId}/");

                        var addedDetail = addedChildDetails
                                          .SingleOrDefault(x => x.HierarchyLevel == targetNodeHierarchyId);

                        var targetNodeToUpdate = treeView.Nodes
                                                 .Find(targetNodeHierarchyId.ToString(), true)
                                                 .SingleOrDefault();

                        var parentNode = detailNode.Parent;
                        DetailInTreeView parentNodeTag = parentNode == null ? null : parentNode.Tag as DetailInTreeView;

                        // Update only if children already loaded for the detail
                        // for which child detail is beening added
                        if (parentNodeTag == null || parentNodeTag.IsThirdGenLoaded)
                        {
                            var detailNodeHierarchyId = detailNodeTag.HierarchyLevel;

                            // Handle case when detail is already present in the selected scope
                            if (targetNodeToUpdate != null)
                            {
                                targetNodeToUpdate.Text = DetailNameInTree(addedDetail.Name,
                                                                           addedDetail.Count);
                                targetNodeToUpdate.Tag = addedDetail;
                            }

                            // Handle case when detail is NOT present in the selected scope
                            if (targetNodeToUpdate == null)
                            {
                                var addedNodeIndex = detailNode.Nodes.Add(new TreeNode
                                {
                                    Text = DetailNameInTree(addedDetail.Name, addedDetail.Count),
                                    Tag  = addedDetail,
                                    Name = targetNodeHierarchyId.ToString()
                                });

                                if (detailNodeTag.IsThirdGenLoaded)
                                {
                                    var addedNode = detailNode.Nodes[addedNodeIndex];

                                    addedChildDetails.ForEach(addedChildDetail =>
                                    {
                                        if (addedDetail.HierarchyLevel ==
                                            addedChildDetail.HierarchyLevel.GetAncestor(1))
                                        {
                                            addedNode.Nodes.Add(
                                                new TreeNode
                                            {
                                                Text = DetailNameInTree(addedChildDetail.Name,
                                                                        addedChildDetail.Count),
                                                Tag  = addedChildDetail,
                                                Name = addedChildDetail.HierarchyLevel.ToString()
                                            });
                                        }
                                    });
                                }
                            }
                        }
                    });

                    ShowMessageDialog("Success added!");
                }
            }
        }
Beispiel #28
0
 public void GetReparentedValue_returns_null_when_newRoot_is_null()
 => Assert.Null(HierarchyId.Parse("/1/").GetReparentedValue(HierarchyId.GetRoot(), newRoot: null));
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.ApplyConfigurationsFromAssembly(typeof(AssemblyMarker).Assembly);

            /*
            modelBuilder.Entity<DetailForReport>(entity =>
            {
                entity.HasNoKey();
                entity.Property(e => e.DetailName);
                entity.Property(e => e.Count);
            });
            */

            #region TestData

            modelBuilder.Entity<Detail>().HasData
            (
                new Detail()
                {
                    DetailId = 1,
                    Name = "Engine #234"
                },
                new Detail()
                {
                    DetailId = 2,
                    Name = "Engine #456"
                },
                new Detail()
                {
                    DetailId = 3,
                    Name = "Crankshaft"
                },
                new Detail()
                {
                    DetailId = 4,
                    Name = "Camshaft"
                },
                new Detail()
                {
                    DetailId = 5,
                    Name = "Piston assembly"
                },
                new Detail()
                {
                    DetailId = 6,
                    Name = "Piston"
                },
                new Detail()
                {
                    DetailId = 7,
                    Name = "Compression ring"
                },
                new Detail()
                {
                    DetailId = 8,
                    Name = "Oil scrapper ring"
                },
                new Detail()
                {
                    DetailId = 9,
                    Name = "Connecting rod"
                },
                new Detail()
                {
                    DetailId = 10,
                    Name = "Cylinder block"
                }
            );

            modelBuilder.Entity<DetailRelation>().HasData
            (
                new DetailRelation()
                {
                    DetailRelationId = 1,
                    DetailId = 1,
                    Count = null,
                    HierarchyId = HierarchyId.Parse("/1/")
                },
                new DetailRelation()
                {
                    DetailRelationId = 2,
                    DetailId = 2,
                    Count = null,
                    HierarchyId = HierarchyId.Parse("/2/")
                },
                new DetailRelation()
                {
                    DetailRelationId = 3,
                    DetailId = 10,
                    Count = 1,
                    HierarchyId = HierarchyId.Parse("/1/10/")
                },
                new DetailRelation()
                {
                    DetailRelationId = 4,
                    DetailId = 3,
                    Count = 1,
                    HierarchyId = HierarchyId.Parse("/1/3/")
                },
                new DetailRelation()
                {
                    DetailRelationId = 5,
                    DetailId = 4,
                    Count = 2,
                    HierarchyId = HierarchyId.Parse("/1/4/")
                },
                new DetailRelation()
                {
                    DetailRelationId = 6,
                    DetailId = 5,
                    Count = 4,
                    HierarchyId = HierarchyId.Parse("/1/5/")
                },
                new DetailRelation()
                {
                    DetailRelationId = 7,
                    DetailId = 6,
                    Count = 1,
                    HierarchyId = HierarchyId.Parse("/1/5/6/")
                },
                new DetailRelation()
                {
                    DetailRelationId = 8,
                    DetailId = 7,
                    Count = 2,
                    HierarchyId = HierarchyId.Parse("/1/5/7/")
                },
                new DetailRelation()
                {
                    DetailRelationId = 9,
                    DetailId = 8,
                    Count = 1,
                    HierarchyId = HierarchyId.Parse("/1/5/8/")
                },
                new DetailRelation()
                {
                    DetailRelationId = 10,
                    DetailId = 9,
                    Count = 4,
                    HierarchyId = HierarchyId.Parse("/1/9/")
                }
            );

            #endregion TestData
        }
Beispiel #30
0
 public static SqlHierarchyId Parse(SqlString input) => new SqlHierarchyId(HierarchyId.Parse((string)input));