George Dim
George Dim

Reputation: 85

Need Help for Join tables in Linq on ASP.NET Core

basically i am working on ASP.NET Core and I have an FromSqlRaw statement which filters and keeps some ids in a value of a talbe (ActiveCalls). Then with Linq I filter another table of database (AppUsers). My goal is to keep all columns of Appusers with Ids i take from ActiveCalls.

Code for SqlRaw with Ids result : (13) Correct!

var results = _context.ActiveCalls.FromSqlRaw("SELECT web_userid from ActiveCalls where TimeReceived>'2021-01-01' and GeoX > 23.8097593342164 and GeoX < 23.8838031312548 and GeoY > 38.1026672246045 and GeoY < 38.1607577524088 group by web_userid");

Code for Linq with data :Result (2281) Correct!

appusers = appusers.Where(s => s.LastCall >= start && s.LastCall <= end);

Code for Join tables to keep only Records of AppUsers based on Ids i found on ActiveCalls. Result(10) Wrong!

 appusers = from res in results
                     join ap in appusers
                     on res.web_userid equals ap.Id
                     select ap;

I have to take the result with Linq and those 3 steps and not merge all in on Sql query

Upvotes: 0

Views: 164

Answers (2)

Varun Anand
Varun Anand

Reputation: 39

Try Somthing like this

var results = _context.ActiveCalls.FromSqlRaw("SELECT web_userid from ActiveCalls where TimeReceived>'2021-01-01' and GeoX >
23.8097593342164 and GeoX < 23.8838031312548 and GeoY > 38.1026672246045 and GeoY < 38.1607577524088 group by web_userid");

appusers = appusers.Where(s => s.LastCall >= start && s.LastCall <= end && results.web_userid.contains(s.Id));

Upvotes: 0

Svyatoslav Danyliv
Svyatoslav Danyliv

Reputation: 27346

I don't get an idea of using FromSqlRaw in this case.

var results = 
   from ac in _context.ActiveCalls 
   where ac.TimeReceived > DateTime.Parse("2021-01-01") 
     && ac.GeoX > 23.8097593342164 
     && ac.GeoX < 23.8838031312548 
     && ac.GeoY > 38.1026672246045 
     && ac.GeoY < 38.1607577524088
   select ac.web_userid;

results = results.Distinct();

var appusers = _context.AppUsers.AsQueryable();
appusers = appusers.Where(s => s.LastCall >= start && s.LastCall <= end);

appusers = 
   from res in results
   join ap in appusers on res.web_userid equals ap.Id
   select ap;

If you still does not have correct result, it means that AppUser.Id is not web_userid

Upvotes: 1

Related Questions