Shanmugam R
Shanmugam R

Reputation: 1

LINQ IQueryable issue when joining 2 tables in Entity Framework

I'm using EF pulling data into Angular UI. This EF is code-first mapped and I'm trying to get data from 2 tables Tabl1 and T2 using union. The current code gets data from below code from 1 table

var utility = new QueryableUtility<Table1Entity>();

var queryable = utility.findQueryable(
   Request,
   db.Table1.AsQueryable(),
   QueryParamArray.Instance.FSParameterArray,
   new Table1Entity()
);

I changed the code to below to get common fields from both tables and use UNION

var t1 = 
   db
   .Table1
   .Select(x => new Table1Dto {
      Id = x.Id,
      Name = x.Name,
      Status = x.Status
   }).ToList();

var t2 = 
   db
   .Table2
   .Select(x => new Table2Dto {
      Id = x.Id,
      Name = x.Name,
      Status = x.Status
   }).ToList();

var qry = t1.Union(t2);

var utility = new QueryableUtility<Table1Entity>();

var queryable = utility.findQueryable(
   Request,
   qry.AsQueryable(),
   QueryParamArray.Instance.FSParameterArray,
   new Table1Entity()
);

In the line qry.AsQueryable(), I'm getting below error:

cannot convert from system.linqIqueriable to system.linqIqueriable

Upvotes: 0

Views: 242

Answers (1)

Dave Cousineau
Dave Cousineau

Reputation: 13198

t1 and t2 are no longer IQueryables since you have called .ToList(). And so neither is qry. You call .AsQueryable() to get around this, but what you then have is something from LINQ to Objects pretending to be a 'real' IQueryable when it isn't. I'm not sure what QueryableUtility is, but it probably wants 'real' IQueryables to work with.

The first step would be to remove the .ToList() calls and the .AsQueryable() call should then also be unnecessary.

From there you may or may not have other query-related errors.

Since you are calling Union, the types of the two queries must be the same. You could possibly use anonymous types to be able to merge them:

var t1 = 
   db
   .Table1
   .Select(x => new {
      Id = x.Id,
      Name = x.Name,
      Status = x.Status
   });

var t2 = 
   db
   .Table2
   .Select(x => new {
      Id = x.Id,
      Name = x.Name,
      Status = x.Status
   });

var qry = t1.Union(t2);

var utility = new QueryableUtility<Table1Entity>();

var queryable = utility.findQueryable(
   Request,
   qry,
   QueryParamArray.Instance.FSParameterArray,
   new Table1Entity()
);

Upvotes: 3

Related Questions