C
C#10mo ago
CaptainSh4dow

❔ [EFCore] What is the right approach to generate hierarchy id for new child entity?

I Use SQLServer & EF Core. been struggling to find the right approach to generate new h-id for new child entities for a while now. and most approaches online are just straight up inserting duplicates or doing multiple queries with really possible scare-y edge cases that can cause alot of trouble.
3 Replies
CaptainSh4dow
CaptainSh4dow10mo ago
like this article shows a method where there guy inserts another /1/ which is a violation iirc. you can't have duplicate h-id paths https://www.meziantou.net/using-hierarchyid-with-entity-framework-core.htm
Meziantou's blog
Using SQL Server HierarchyId with Entity Framework Core - Gérald Ba...
In this post, I describe how to use the HierarchyId data type with Entity Framework Core.
No description
CaptainSh4dow
CaptainSh4dow10mo ago
my current approach that does two queries
public static HierarchyId GeneratePathForChild(HierarchyId? parent, HierarchyId? lastChildId)
{

//Handling Fatherless Entities.
if (parent is null)
return HierarchyId.Parse("/");

//Handling Entities With No Sister Entities.
if (lastChildId is null)
return HierarchyId.Parse($"{parent}{1}/");

//Handling Entities With Sister Entities
var lastDigit = lastChildId.ToString().Split("/", StringSplitOptions.RemoveEmptyEntries).Last();
var lastDigitNumber = int.Parse(lastDigit);
return HierarchyId.Parse($"{parent}{lastDigitNumber + 1}/");

}
public static HierarchyId GeneratePathForChild(HierarchyId? parent, HierarchyId? lastChildId)
{

//Handling Fatherless Entities.
if (parent is null)
return HierarchyId.Parse("/");

//Handling Entities With No Sister Entities.
if (lastChildId is null)
return HierarchyId.Parse($"{parent}{1}/");

//Handling Entities With Sister Entities
var lastDigit = lastChildId.ToString().Split("/", StringSplitOptions.RemoveEmptyEntries).Last();
var lastDigitNumber = int.Parse(lastDigit);
return HierarchyId.Parse($"{parent}{lastDigitNumber + 1}/");

}
one query to load the parent. and the other to load the last child.
Accord
Accord10mo ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity. Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts