Skip to content

Set operations: support when placed after client evaluation in projection #16243

Closed as not planned

Description

@roji

Test case:

public virtual Task Client_eval_Union_FirstOrDefault(bool isAsync)
    => AssertFirstOrDefault<Customer>(
        isAsync, cs => cs
            .Select(c => ClientSideMethod(c))
            .Union(cs));

Can probably be punted post-3.0 (can be easily worked around).

Activity

  1. added this to the Backlog milestone on Jun 28, 2019
  2. cyptus commented on Mar 12, 2020

    @cyptus

    the following query is working as expected but fails in combination with union with the exception System.InvalidOperationException: 'Can't process set operations after client evaluation, consider moving the operation before the last Select() call (see issue #16243)':

    var query1 = context.Articles.Where(x => x.IsArchived == true).Select(x => new ArticleDto()
    {
        ArticleId = x.ArticleId,
        IsArchived = true,
        Comments = x.Comments.Select(c => new CommentDto()
        {
            CommentId = c.CommentId
        })
    });

    is working, but failing with union:

    var query1 = context.Articles.Where(x => x.IsArchived == true).Select(x => new ArticleDto()
    {
        ArticleId = x.ArticleId,
        IsArchived = true,
        Comments = x.Comments.Select(c => new CommentDto()
        {
            CommentId = c.CommentId
        })
    });
    
    var query2 = context.Articles.Where(x => x.IsArchived == false).Select(x => new ArticleDto()
    {
        ArticleId = x.ArticleId,
        IsArchived = false,
        Comments = x.Comments.Select(c => new CommentDto()
        {
            CommentId = c.CommentId
        })
    });
    
    var result = query1.Union(query2).ToList();

    when removing Comments selection the query works fine within union.

    Is this the same issue like from @roji 's example as the comments selection itself is not a client evaulation?
    When using InMemoryDatabase instead of SQL this works fine.

    Full example code: https://gist.github.com/cyptus/ef80cb7a58aa08ab06da4cd42da1ec06

  3. roji commented on Mar 15, 2020

    @roji
    MemberAuthor

    Yes, your query is the same as what I posted originally. You should be able to rewrite this query to work by moving the Union earlier in your query, which also makes for less duplication:

    context.Articles
        .Where(x => x.IsArchived == true)
        .Union(context.Articles.Where(x => x.IsArchived == false)
        .Select(x => new ArticleDto() {
            ArticleId = x.ArticleId,
            IsArchived = x.IsArchived,
            Comments = x.Comments.Select(c => new CommentDto()
            {
                CommentId = c.CommentId
            })
        })
        .ToList();

    (of course, in your particular query you don't need a Union at all since you're just doing it over IsArchived true/false, but I'm assuming this is only a minimal example of some sort).

  4. Maleaume commented on Mar 31, 2020

    @Maleaume

    Your example is not complete because you request on same table
    I have the use case with two tables with one different column but i want to make a union in a common object. I Can't I have the same error

    [TableA]
    class A {
        public string NameA;
        public string DescriptionA;
    }
    
    [TableB]
    class B {
        public string NameB;
        public string DescriptionB;
    }
    
    class UnionClass
    {
        public string Name;
        public string Description;
    }

    I would like to

    var queryableA  = Context.A.select( x => new UnionClass{ Name =x.NameA,Description = x.DescriptionA);
    var queryableB = Context.Bselect( x => new UnionClass{ Name =x.NameB,Description = x.DescriptionB);
    
    var queryUnion = queryableA.Union(queryableB)
    var result = queryUnion .Select( x=> x.Name.contains("RE));
  5. brandonsmith86 commented on Mar 31, 2020

    @brandonsmith86

    I have the same use-case as @Maleaume. How do you suggest we workaround the issue in this case?

  6. BeejeeDS commented on May 1, 2020

    @BeejeeDS

    I have the same scenario as @Maleaume.
    I even want to add paging to it, so i'll be needing a Skip and Take after the Union.

  7. roji commented on May 1, 2020

    @roji
    MemberAuthor

    @Maleaume @brandonsmith86 @BeejeeDS the only issue here is with set operations after a client projection - as long as you write your query to place the union before that, there's no issue. You can typically do this by projecting to an anonymous type (which works fine and doesn't require client translation) and doing everything you need on that. If you need to project out to your own type, do that at the end.

    For example:

    var result = ctx.A
        .Select(a => new { Name = a.NameA, Description = a.DescriptionA })
        .Union(ctx.B
            .Select(b => new { Name = b.NameB, Description = b.DescriptionB }))
        .Where(x => x.Name.StartsWith("a"))
        // Add any further operations to be executed in the database here
        .Select(x => new UnionClass
        {
            Name = x.Name,
            Description = x.Description
        })
        .ToList();
  8. fingers10 commented on May 11, 2020

    @fingers10

    I have the same issue but I'm trying Union for two Join queries.

    var result = await _context.Stage.Join(_context.User, s => s.UserNo, u => u.UserNo, (s, u) => new { s, u })
               .Select(c => new { Detail = $"{c.s.Description.Trim()} - {c.u.UserDescription.Trim()}", Id = c.s.Id })
                  .Union(
                    _context.Stage.Join(_context.UserGroup, s => s.UserGroupNo, ug => ug.UserGroupNo, (s, ug) => new { s, ug })
               .Select(c => new { Detail = $"{c.s.Description.Trim()} - {c.ug.GroupDesription.Trim()}", Id = c.s.Id })
                              )
                              .Where(c => c.Id == Id)
                              .Select(x => x.Detail)
                              .ToListAsync();

    and I get the same error. Am I doing anything wrong here? Please assist

  9. roji commented on May 11, 2020

    @roji
    MemberAuthor

    @fingers10's error repros for me, although removing the Union shows the query working without any sort of client evaluation. @smitpatel any ideas?

    Repro code
    class Program
    {
        static async Task Main(string[] args)
        {
            using var ctx = new BlogContext();
            ctx.Database.EnsureDeleted();
            ctx.Database.EnsureCreated();
    
            var result = await ctx.Stage
                .Join(ctx.User, s => s.UserNo, u => u.UserNo, (s, u) => new { s, u })
                .Select(c => new { Detail = $"{c.s.Description.Trim()} - {c.u.UserDescription.Trim()}", Id = c.s.Id })
                .Union(
                    ctx.Stage
                        .Join(ctx.UserGroup, s => s.UserGroupNo, ug => ug.UserGroupNo, (s, ug) => new { s, ug })
                        .Select(c => new { Detail = $"{c.s.Description.Trim()} - {c.ug.GroupDesription.Trim()}", Id = c.s.Id })
                )
                .Where(c => c.Id == 8)
                .ToListAsync();
        }
    }
    
    public class BlogContext : DbContext
    {
        public DbSet<Stage> Stage { get; set; }
        public DbSet<User> User { get; set; }
        public DbSet<UserGroup> UserGroup { get; set; }
    
        static ILoggerFactory ContextLoggerFactory
            => LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseSqlServer(@"Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0")
                .EnableSensitiveDataLogging()
                .UseLoggerFactory(ContextLoggerFactory);
    }
    
    public class Stage
    {
        public int Id { get; set; }
        public int UserNo { get; set; }
        public int UserGroupNo { get; set; }
        public string Description { get; set; }
    }
    
    public class User
    {
        public int Id { get; set; }
        public int UserNo { get; set; }
        public string UserDescription { get; set; }
    }
    
    public class UserGroup
    {
        public int Id { get; set; }
        public int UserNo { get; set; }
        public string GroupDesription { get; set; }
        public int UserGroupNo { get; set; }
    }
  10. smitpatel commented on May 11, 2020

    @smitpatel
    Contributor

    Interpolated string is client evaluation.

  11. roji commented on May 11, 2020

    @roji
    MemberAuthor

    Of course, I somehow missed that, thanks...

    @fingers10 you'll need to rewrite your query to move the trimming out to after the Select:

    var result = await ctx.Stage
        .Join(ctx.User, s => s.UserNo, u => u.UserNo, (s, u) => new { s, u })
        .Select(c => new { Detail = c.s.Description, Description = c.u.UserDescription, Id = c.s.Id })
        .Union(
            ctx.Stage
                .Join(ctx.UserGroup, s => s.UserGroupNo, ug => ug.UserGroupNo, (s, ug) => new { s, ug })
                .Select(c => new { Detail = c.s.Description, Description = c.ug.GroupDesription, Id = c.s.Id })
        )
        .Where(c => c.Id == 8)
        .Select(c => new { Detail = $"{c.Detail.Trim()} - {c.Description.Trim()}" })
        .ToListAsync();

    FWIW that also removes the needless duplication.

  12. fingers10 commented on May 12, 2020

    @fingers10

    @roji I'm getting this error - Set operations over different store types are currently unsupported, after rewriting the query as you mentioned.

  13. roji commented on May 12, 2020

    @roji
    MemberAuthor

    @fingers10 you need to post your full query (and preferably model as well) for me to be able to help. The query I posted above worked for me.

  14. 13 remaining items

  15. nmoreaud commented on Feb 24, 2021

    @nmoreaud

    I would like to

    var queryableA  = Context.A.select( x => new UnionClass{ Name =x.NameA,Description = x.DescriptionA);
    var queryableB = Context.Bselect( x => new UnionClass{ Name =x.NameB,Description = x.DescriptionB);
    
    var queryUnion = queryableA.Union(queryableB)
    var result = queryUnion .Select( x=> x.Name.contains("RE));

    I have the same issue with inheritance. I guess it would be a use case for TPC but it is not supported yet and I use efcore 3 (next version doesn't have Oracle driver yet). I have an existing db with multiple tables that share 90% of their fields.
    I have something like this:

    class BaseClass
    {
        public string Name;
        public string Description;
    }
    
    [TableA]
    class A : BaseClass {
        public string FieldA;
    }
    
    [TableB]
    class B : BaseClass {
        public string FieldB;
    }
    
    
    var queryableA  = Context.A.select( x => (BaseClass) x);
    var queryableB = Context.B.select( x => (BaseClass) x);
    
    var queryUnion = queryableA.Union(queryableB)
    var result = Context.C.Where(c => queryUnion.Select(u => u.Name).Contains(c.Name));

    The same request works fine if I retrieve the Name field instead of BaseClass. However, if I need 2 fields I am doomed!
    I spend lot of time to make complex SQL queries compatible with efcore where I would have written by hand the same SQL request 10x faster ; this is the downside of ORM and multi-database compatibility.

  16. xrkolovos commented on Aug 3, 2021

    @xrkolovos

    Hello.

    Any thoughs on this issue? Is by any chance going to be in .net 6 wave?

  17. ajcvickers commented on Aug 3, 2021

    @ajcvickers
    Contributor

    @xrkolovos This issue is in the Backlog milestone. This means that it is not planned for the next release (EF Core 6.0). We will re-assess the backlog following the this release and consider this item at that time. However, keep in mind that there are many other high priority features with which it will be competing for resources.

  18. Pentadome commented on May 20, 2022

    @Pentadome

    For me, DateTimeOffset.ToString() caused .Concats to fail. However DateTimeOffset.Day.Tostring() + "-" + DateTimeOffset.Month.Tostring() + "-" + DateTimeOffset.Year.Tostring() did work.

    Kinda silly, but I hope it helped someone

  19. removed this from the Backlog milestone on May 20, 2022
  20. roji commented on May 24, 2022

    @roji
    MemberAuthor

    For users arriving here, most of problematic user queries we've seen involve client evaluation (i.e. constructs which can't be translated to SQL) which can simply be moved after the set operation; that is the optimal solution (see above for examples).

    The remaining cases where this cannot be done involve e.g. client evaluation only on one side of the set operation (e.g. the OP). Translating this would be possible only by synthesizing a discriminator allowing us to know which row comes from which side, and applying the client evaluation based on that. While possible, this is quite complex and we haven't seen any actual request for it.

    For the record, for Concat (UNION ALL) it's also possible to evaluate the operator on the client-side, since it doesn't involve bring any excess data to the client. This isn't true for the other set operations.

  21. added theissue type on Jun 15, 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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions