Search code examples
c#linq.net-coreentity-framework-corelinq-to-entities

Concatenate Entity Framework Core models in linq query that are derived from different size varchar columns


Details: using linq method syntax, and database-first Entity Framework Core models.

Database is SQL Server.

I have 3 tables, the columns from first two tables are of datatype varchar(256) and corresponding entity property has data annotation StringLength(256). The column from the 3rd table is defined as varchar(20) and corresponding entity property has data annotation StringLength(20).

Query:

ThingList = await ctx.Table1.Select(t1 => t1.Thing)
            .Concat(ctx.Table2.Select(t2 => t2.Thing))
            .Concat(ctx.Table3.Select(t3 => t3.Thing))
            .Distinct().ToListAsync();

The query works when I concatenate only the first two tables, but then doesn't work when I try to include the third. I'm assuming this is because of the difference in sizes.

How do I get around this? Thank you in advance.


Solution

  • Found out what the issue is. This is a known problem: https://github.com/dotnet/efcore/issues/24707 https://github.com/dotnet/efcore/issues/19129 EF query fails without Convert.ToString()

    Fixed my issue by changing my query to this:

            ThingList = await ctx.Table1.Select(t1 => Convert.ToString(t1.Thing))
                .Concat(ctx.Table2.Select(t2 => Convert.ToString(t2.Thing)))
                .Concat(ctx.Table3.Select(t3 => Convert.ToString(t3.Thing)))
                .Distinct().ToListAsync();