question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

PostgreSQL Unnest not working?

See original GitHub issue

Let’s assume a table in PostgreSQL defined with EF Core:

public class Fact
{
        public Guid FactId { get; set; }
        public string[] Tags { get; set; }
}

And now let’s try to do any query with unnest in it…

var l2c = ctx.CreateLinqToDbContext();
var query = await (from f in ctx.Facts
                 from t in l2c.Unnest(f.Tags)
                 select t).ToArrayAsyncLinqToDB();

The exception is:

System.InvalidOperationException
variable 'f' of type 'L2DbBugRepro.Fact' referenced from scope '', but it is not defined
   at System.Linq.Expressions.Compiler.VariableBinder.Reference(ParameterExpression node, VariableStorageKind storage)
   at System.Linq.Expressions.Compiler.VariableBinder.VisitParameter(ParameterExpression node)
   at System.Linq.Expressions.ParameterExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.Compiler.VariableBinder.Visit(Expression node)
   at System.Linq.Expressions.ExpressionVisitor.Visit(ReadOnlyCollection`1 nodes)
   at System.Linq.Expressions.Compiler.VariableBinder.VisitLambda[T](Expression`1 node)
   at System.Linq.Expressions.Expression`1.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.Compiler.VariableBinder.Visit(Expression node)
   at System.Linq.Expressions.Compiler.LambdaCompiler.Compile(LambdaExpression lambda)
   at System.Linq.Expressions.LambdaExpression.Compile()
   at LinqToDB.EntityFrameworkCore.LinqToDBForEFToolsImplDefault.EvaluateExpression(Expression expr)
   at LinqToDB.EntityFrameworkCore.LinqToDBForEFToolsImplDefault.EvaluateExpression(Expression expr)
   at System.Linq.Enumerable.SelectIListIterator`2.ToArray()
   at LinqToDB.EntityFrameworkCore.LinqToDBForEFToolsImplDefault.<>c__DisplayClass39_0.<TransformExpression>g__LocalTransform|0(Expression e)
   at LinqToDB.EntityFrameworkCore.LinqToDBForEFToolsImplDefault.<>c__DisplayClass39_0.<TransformExpression>b__1(Expression e)
   at LinqToDB.Expressions.Extensions.<>c.<Transform>b__16_0(Func`2 f, Expression e)
   at LinqToDB.Expressions.TransformInfoVisitor`1.Transform(Expression expr)
   at LinqToDB.Expressions.TransformInfoVisitor`1.Transform(Expression expr)
   at LinqToDB.Expressions.TransformInfoVisitor`1.Transform(Expression expr)
   at LinqToDB.Expressions.TransformInfoVisitor`1.Transform[T](IList`1 source)
   at LinqToDB.Expressions.TransformInfoVisitor`1.Transform(Expression expr)
   at LinqToDB.Expressions.Extensions.Transform(Expression expr, Func`2 func)
   at LinqToDB.EntityFrameworkCore.LinqToDBForEFToolsImplDefault.TransformExpression(Expression expression, IDataContext dc, DbContext ctx, IModel model)
   at LinqToDB.EntityFrameworkCore.LinqToDBForEFTools.TransformExpression(Expression expression, IDataContext dc, DbContext ctx, IModel model)
   at LinqToDB.EntityFrameworkCore.LinqToDBForEFToolsDataConnection.ProcessExpression(Expression expression)
   at LinqToDB.Linq.Query`1.GetQuery(IDataContext dataContext, Expression& expr, Boolean& dependsOnParameters)
   at LinqToDB.Linq.ExpressionQuery`1.GetQuery(Expression& expression, Boolean cache, Boolean& dependsOnParameters)
   at LinqToDB.Linq.ExpressionQuery`1.<GetForEachAsync>d__19.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
   at LinqToDB.AsyncExtensions.<ToArrayAsync>d__9`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

I thought something is wrong because I’m using a different l2d context, so I tried this:


var l2c = ctx.CreateLinqToDbContext();
var query = await (from f in l2c.GetTable<Fact>()
                 from t in l2c.Unnest(f.Tags)
                 select t).ToArrayAsyncLinqToDB();

But no, the error was the same.

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
Evengardcommented, Mar 24, 2022

The full repro as follows:

Repro
using LinqToDB;
using LinqToDB.DataProvider.PostgreSQL;
using LinqToDB.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.ComponentModel.DataAnnotations;

namespace L2DbBugRepro
{
    class Program
    {

        static List<object> storage = new List<object>();

        static async Task Main(string[] args)
        {
            LinqToDBForEFTools.Initialize();
            
            await using (var ctx = new BlogContext())
            {
                await ctx.Database.EnsureDeletedAsync();
                await ctx.Database.EnsureCreatedAsync();

                ctx.Facts.Add(new Fact
                {
                    FactId = Guid.NewGuid(),
                    Tags = new[]{ "one", "two" },
                });
                await ctx.SaveChangesAsync();
            }
            await using (var ctx = new BlogContext())
            {
                var l2c = ctx.CreateLinqToDbContext();
                var query = await (from f in l2c.GetTable<Fact>()
                                 from t in l2c.Unnest(f.Tags)
                                 select t).ToArrayAsyncLinqToDB();
            }

        }
    }

    public class BlogContext : DbContext
    {
        public DbSet<Fact> Facts { get; set; }

        static ILoggerFactory ContextLoggerFactory
            => LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseNpgsql(@"Host=localhost;Username=root;Password=rootpass;Database=Testing")
    .EnableSensitiveDataLogging()
                .UseLoggerFactory(ContextLoggerFactory);

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        }
    }

    public class Fact
    {
        [Key]
        public Guid FactId { get; set; }

        public string[] Tags { get; set; }
    }

}
0reactions
Evengardcommented, Apr 7, 2022

Never mind, after digging into the project structure a little bit got it working. Thanks, seems to work pretty well!

Read more comments on GitHub >

github_iconTop Results From Across the Web

PSQL unnest function not working as expected
Query: SELECT unnest(team) FROM table_of_teams WHERE team LIKE '%akg%';.
Read more >
PostgreSQL Unnest Function: Syntax & Essential Queries
unnest() is PostgreSQL function to to set the elements in table-like structure. Unnsest function must be provided with an array as an argument....
Read more >
How does Unnest Function work in PostgreSQL?
Unnest: This function we defined in PostgreSQL to set the element in a table-like structure. We have used unnest element with text as...
Read more >
PostgreSQL UNNEST() function
The unnest() function in PostgreSQL is used to expand an array into a set of rows. It takes an array as input and...
Read more >
PostgreSQL UNNEST() Function With Examples
PostgreSQL provides a built-in function named UNNEST() that accepts an array as an argument and expands the given array into a set of...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found