efcore.pg
efcore.pg copied to clipboard
ExecuteUpdate support Ltree
Require move path and all sub to new path.
UnitTest example
[ConditionalFact]
public void ExecuteUpdate()
{
using var ctx = CreateContext();
var originLtree = ctx.LTreeEntities.Where(y => y.Path == "Top.Science")
.Select(y => new { y.Path, NLevel = y.Path.NLevel - 1 })
.First();
var lTreeEntities = ctx.LTreeEntities.Where(
r => r.Path.IsDescendantOf(originLtree.Path));
var resultPaths = lTreeEntities
.Select(r => new LTree($"Top.Hobbies.{r.Path.Subpath(originLtree.NLevel)}")).ToList();
lTreeEntities.ExecuteUpdate(
r => r.SetProperty(y => y.Path, y => new LTree($"Top.Hobbies.{y.Path.Subpath(originLtree.NLevel)}")));
}
resultPaths
System.InvalidOperationException: The LINQ expression 'DbSet<LTreeEntity>()
.Where(l => l.Path.IsDescendantOf(__originLtree_Path_0))
.ExecuteUpdate(r => r.SetProperty<LTree>(
propertyExpression: y => y.Path,
valueExpression: y => new LTree(string.Format(
format: "Top.Hobbies.{0}",
arg0: (object)y.Path.Subpath(__originLtree_NLevel_1)))))' could not be translated. Additional information: The following 'SetProperty' failed to translate: 'SetProperty(y => y.Path, y => new LTree(string.Format(
format: "Top.Hobbies.{0}",
arg0: (object)y.Path.Subpath(__originLtree_NLevel_1))))'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
Sorry for not giving this my attention earlier.
You haven't posted the exception details, but it's likely that your ExecuteUpdate is failing because you're trying to use string.Format(), which isn't supported.
@Off-DutY I'm not sure if my answer is still relevant to you, but I have a similar problem and managed to get it working with a few changes.
static void ReparentDb(EfPostgresLtreeContext context, Ugi parent, IEnumerable<Ugi> children)
{
var childrenHierarchies = children.Select(x => x.Hierarchy).ToList();
context.Ugis.Where(x => childrenHierarchies.Any(c => x.Hierarchy.IsDescendantOf(c)))
.ExecuteUpdate(x =>
x.SetProperty(
y => y.Hierarchy,
y => (LTree)(parent.Hierarchy + "." + y.Hierarchy)));
}
So on the last line (LTree)(parent.Hierarchy + "." + y.Hierarchy)) I replaced string interpolation with concatenations and instead of new LTree I used type cast. This translates into the following SQL:
UPDATE "Ugis" AS u
SET "Hierarchy" = CAST(@__p_1 || u."Hierarchy"::text AS ltree)
WHERE EXISTS (
SELECT 1
FROM unnest(@__childrenHierarchies_0) AS c(value)
WHERE u."Hierarchy" <@ c.value)