Skip to content

WHERE .. = ANY() Clause with composite objects not working #2154

Closed

Description

@smblee

Disclaimer: The issue is regarding Npgsql.EntityFrameworkCore.PostgreSQL 2.1.1 but I am posting it here since I am often times using .FromSql with raw sqls (including regarding this issue). If this is still in the wrong project, i will move it.

Steps to reproduce

The query I want to produce:

SELECT * FROM table WHERE (itemauthor, itemtitle) = ANY (('bob', 'hello'), ('frank', 'hi')...) OR
SELECT * FROM table WHERE (itemauthor, itemtitle) IN (VALUES ('bob', 'hello'), ('frank', 'hi')...)

Code I have / problems:

var parameters = new NpgsqlParameter[] {
   new NpgsqlParameter("@items", items.Select(i => new { items.Author, items.Title }).ToList())
};

var query = "Select [...bunch of columns...] from table where (itemauthor, itemtitle) = ANY (:items)";
_context.Query<MyRow>().FromSql(query, parameters).ToList();

This will say something like the type AnonymousType{string, string} is not registered.

I have also tried things like

  new NpgsqlParameter("@items", items.Select(i => $"('{i.Author}', '{i.Title}')").ToList()),
AND...
  new NpgsqlParameter("@items", string.Join(',', items.Select(i => $"('{i.Author}', '{i.Title}')"))

But this throws like an invalid argument at $4 exception.

The issue

Exception message:

System.NotSupportedException: The CLR array type System.Collections.Generic.List`1[<>f__AnonymousType0`2[System.String,System.String]] isn't supported by Npgsql or your PostgreSQL. If you wish to map it to an  PostgreSQL c
omposite type array you need to register it before usage, please refer to the documentation.

Stack trace:

         at Npgsql.TypeMapping.ConnectorTypeMapper.GetByClrType(Type type) in C:\projects\npgsql\src\Npgsql\TypeMapping\ConnectorTypeMapper.cs:line 140
         at Npgsql.NpgsqlParameter.ResolveHandler(ConnectorTypeMapper typeMapper) in C:\projects\npgsql\src\Npgsql\NpgsqlParameter.cs:line 529
         at Npgsql.NpgsqlParameter.Bind(ConnectorTypeMapper typeMapper) in C:\projects\npgsql\src\Npgsql\NpgsqlParameter.cs:line 538
         at Npgsql.NpgsqlCommand.ValidateParameters() in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:line 801
         at Npgsql.NpgsqlCommand.<ExecuteDbDataReader>d__100.MoveNext() in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:line 1233

Further technical details

Npgsql version: NpgSql EntityFramework Core 2.1.1
PostgreSQL version: 9.6
Operating system: Windows

Other details about my project setup: dotnet core 2.0

Activity

  1. YohDeadfall commented on Sep 13, 2018

    @YohDeadfall
    Contributor

    As the exception says the corresponding composite is required in the database. This is because anonymous types are not mapped to records.

    So, you should create a type and a struct which must be mapped to the type.

    FYI, there is a similar issue #2097 to track mapping composites to value tuples.

  2. austindrenski commented on Sep 13, 2018

    @austindrenski
    Contributor

    This would be nice to have, assuming it doesn't break anything else.

    I'm hoping to make some progress on #2097 this weekend. If that goes well, I'll take a look at this too.

  3. smblee commented on Sep 14, 2018

    @smblee
    Author

    @YohDeadfall How can i use a non-anonymous object? If i try creating a different object with 2 fields in it, it still gives the same error. How do i "register" this object ? It would be nice to just be able to do new { field1, field2 } or new Tuple<string,string>(field1, field2)

  4. YohDeadfall commented on Sep 14, 2018

    @YohDeadfall
    Contributor

    You should CREATE TYPE first, make the corresponding CLR class and map it using the MapComposite<T> method as it's said in the docs.

    You can map the type to ValueTuple<string, string>, but then it's not possible to map another PostgreSQL type to that struct. There is a one-to-one relation.

    CREATE TYPE book_info AS (author text, title text);
    public class BookInfo
    {
        public string Author { get; set; }
        public string Title { get; set; }
    }
    // in the static ctor of your DbContext
    NpgsqlConnection.GlobalTypeMapper.MapComposite<BookInfo>();
    new NpgsqlParameter("@items", items.Select(i => new BookInfo { Author = i.Author, Title = i.Title }).ToList())
  5. roji commented on Nov 18, 2018

    @roji
    Member

    Unless I'm mistaken, the expression = ANY (('bob', 'hello'), ('frank', 'hi')...) actually accepts an array of records, and not of composite types. PostgreSQL records are totally ad-hoc, weakly-typed bundles of values, and Npgsql does not provide any way of sending these at the moment. see #2097 for a discussion on mapping CLR value tuples, either to composites or to record types.

    Putting this on the backlog for now, we're unlikely to get around to this anytime soon.

  6. added this to the Backlog milestone on Nov 18, 2018
  7. dhedey commented on Feb 23, 2022

    @dhedey

    If it helps anyone else, I have found quite a neat workaround for these types of queries using the UNNEST command, which can take multiple array parameters and zip them together into columns, which can be joined with the table to filter to the relevant columns.

    The use of the join is also more performant than the ANY/IN pattern in some cases.

    SELECT * FROM table WHERE (itemauthor, itemtitle) = ANY (('bob', 'hello'), ('frank', 'hi')...)
    

    Can be represented with:

     var authorsParameter = new NpgsqlParameter("@authors", NpgsqlDbType.Array | NpgsqlDbType.Varchar)
        { Value = authors.ToList() };
    var titlesParameter = new NpgsqlParameter("@titles", NpgsqlDbType.Array | NpgsqlDbType.Varchar)
        { Value = titles.ToList() };
    
    var results = dbContext.Set<MyRow>()
        .FromSqlInterpolated($@"
    SELECT
        t.*
    FROM UNNEST({authorsParameter}, {titlesParameter}) params (author, title)
    INNER JOIN table t
        ON t.author = params.author
        AND t.title = params.title
    ");
    

    NB - the Varchar can be replaced by other types for parameters which are arrays of other types (eg Bigint) - check out the NpgsqlDbType enum for more details.

  8. roji commented on Apr 30, 2022

    @roji
    Member

    Trying to send a record parameter to PostgreSQL triggers the error: "input of anonymous composite types is not implemented", so I'll go ahead and close this issue.

  9. removed this from the Backlog milestone on Apr 30, 2022
  10. added theissue type on Jun 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions