I've got some C# code with a LINQ query I'm trying to translate to Ruby and am using Sequel as my DB ORM. The linq query just performs some joins and then returns an anonymous object containing references to the joined entities. I've got the code translated and operating correctly but it just returns all of the columns from each table and I'd like to wrap each set of columns up in its own object similarly to how it is done in the C# code.
LINQ Query
from s in slots
join tu in _dbContext.table_usages on s.id equals tu.slot_id
join r in _dbContext.Reservations on tu.reservation_id equals r.ReservationID
join o in _dbContext.orders on r.OrderID equals o.OrderID
join c in _dbContext.Contacts on r.ContactID equals c.ContactID
where tu.reservation_id != null &&
r.state != ReservationStates.Cancelled
select new { SlotId = s.id, Reservation = r, Order = o, Contact = c, TableUsage = tu };
Ruby Code:
select(:slots__id, :reservations.*, :orders.*, :restaurant_customers.*, :table_usages.*)
.filter(slots__restaurant_id: restaurant_id, slots__removed: false)
.filter(slots__slot_time: start_time..end_time)
.join(:table_usages, slot_id: :id)
.join(:reservations, id: :table_usages__reservation_id)
.join(:orders, id: :reservations__order_id)
.join(:restaurant_customers, id: :reservations__contact_id)
.filter('table_usages.reservation_id is not null')
.filter('reservations.state != ?', ReservationStates.cancelled)
I'm unable to find a way of accomplishing this via the docs but I thought I would see if anyone has done something similar in a way that I haven't thought of yet.
Thanks!
I'm assuming you are just referring to the last two lines:
.filter('table_usages.reservation_id is not null')
.filter('reservations.state != ?', ReservationStates.cancelled)
Which you could handle via:
.exclude(:table_usages__reservation_id=>nil)
.exclude(:reservations__states=>ReservationStates.cancelled)
exclude operates as an inverse filter.
Related
I'm quite new to entity framework and I'm trying to use the join clause on two entities as follows.
var alertlist = from elogAlert in yangkeeDBEntity.Yang_Kee_Logistics_Pte_Ltd_ELog_Tablet_Alert
where elogAlert.No_ != null
join elogAlertDetail in yangkeeDBEntity. Yang_Kee_Logistics_Pte_Ltd_ELog_Tablet_Alert_Details
on elogAlert.No_ == elogAlertDetail.AlertID
where elogalertdetail.employee_id == driverid
select new
{
elogalertdetail.employee_id,
elogalertdetail.alert_id,
elogalertdetail.no_,
elogalertdetail.status,
elogalertdetail.created_by,
elogalertdetail.date_created,
};
Hi from the above code I'm getting two errors saying
'Error 1 The name 'elogAlertDetail' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.' and 'linq joint type inference failed to call 'join' error '
Currently the two tables does not have any data. Ill be happy if anyone can help me with this situation
you cant use == when joining with Linq. You need to use equals.
Note that it is not the method .Equals(..) but the keyword
from elogAlert in yangkeeDBEntity.Yang_Kee_Logistics_Pte_Ltd_ELog_Tablet_Alert
join elogAlertDetail in yangkeeDBEntity.Yang_Kee_Logistics_Pte_Ltd_ELog_Tablet_Alert_Details
on elogAlert.No_ equals elogAlertDetail.AlertID //this line has equals instead of ==
where elogAlert.No_ != null
where elogalertdetail.employee_id == driverid
select new
{
elogalertdetail.employee_id,
elogalertdetail.alert_id,
elogalertdetail.no_,
elogalertdetail.status,
elogalertdetail.created_by,
elogalertdetail.date_created,
};
Look at the documentaion on Linq join
The error you have relates to the order of arguments around the equals operand on join.
The joined table MUST be the RHS of the equals, and the LHS must be in the row you are joining to.
In this instance yangkeeDBEntity is not in the elogAlert row
CF the example in MSDN
from c in categories
join p in products on c equals p.Category into ps
from p in ps
select new { Category = c, p.ProductName };
c is in the row you are joining from, p.category is on the table you are joining to
in addition you also need to use the word equals not == as mentioned above
I have a form with some indexes based on a document type.
I want to build my linq-to-sql query based on those index. The user might fill just some indexes or all of then.
I would need somenthing like that
Gedi.Models.OperacoesModel.indexMatrix[] IndexMatrixArr = (from a in context.sistema_Documentos
join b in context.sistema_Indexacao on a.id equals b.idDocumento
join c in context.sistema_Indexes on a.idDocType equals c.id
join d in context.sistema_DocType_Index on c.id equals d.docTypeId
where d.docTypeId == idTipo and "BUILT STRING"
orderby b.idIndice ascending
select new Gedi.Models.OperacoesModel.indexMatrix {
idDocumento = a.id,
idIndice = b.idIndice,
valor = b.valor
}).Distinct().ToArray();
This built string should be buit early in the code something like
field1 == a and field2 == b
Is this possible?
Your goal is to create expression dynamicaly, as far as I can see. And there are no way just to put string in linq query and make it work in simple linq world - that's the bad news. But I also have a good news for you - there are some way exist to create your query dynamicaly:expression tree, dynamic LINQ.
I have the following LINQ query, that is returning the results that I expect, but it does not "feel" right.
Basically it is a left join. I need ALL records from the UserProfile table.
Then the LastWinnerDate is a single record from the winner table (possible multiple records) indicating the DateTime the last record was entered in that table for the user.
WinnerCount is the number of records for the user in the winner table (possible multiple records).
Video1 is basically a bool indicating there is, or is not a record for the user in the winner table matching on a third table Objective (should be 1 or 0 rows).
Quiz1 is same as Video 1 matching another record from Objective Table (should be 1 or 0 rows).
Video and Quiz is repeated 12 times because it is for a report to be displayed to a user listing all user records and indicate if they have met the objectives.
var objectiveIds = new List<int>();
objectiveIds.AddRange(GetObjectiveIds(objectiveName, false));
var q =
from up in MetaData.UserProfile
select new RankingDTO
{
UserId = up.UserID,
FirstName = up.FirstName,
LastName = up.LastName,
LastWinnerDate = (
from winner in MetaData.Winner
where objectiveIds.Contains(winner.ObjectiveID)
where winner.Active
where winner.UserID == up.UserID
orderby winner.CreatedOn descending
select winner.CreatedOn).First(),
WinnerCount = (
from winner in MetaData.Winner
where objectiveIds.Contains(winner.ObjectiveID)
where winner.Active
where winner.UserID == up.UserID
orderby winner.CreatedOn descending
select winner).Count(),
Video1 = (
from winner in MetaData.Winner
join o in MetaData.Objective on winner.ObjectiveID equals o.ObjectiveID
where o.ObjectiveNm == Constants.Promotions.SecVideo1
where winner.Active
where winner.UserID == up.UserID
select winner).Count(),
Quiz1 = (
from winner2 in MetaData.Winner
join o2 in MetaData.Objective on winner2.ObjectiveID equals o2.ObjectiveID
where o2.ObjectiveNm == Constants.Promotions.SecQuiz1
where winner2.Active
where winner2.UserID == up.UserID
select winner2).Count(),
};
You're repeating join winners table part several times. In order to avoid it you can break it into several consequent Selects. So instead of having one huge select, you can make two selects with lesser code. In your example I would first of all select winner2 variable before selecting other result properties:
var q1 =
from up in MetaData.UserProfile
select new {up,
winners = from winner in MetaData.Winner
where winner.Active
where winner.UserID == up.UserID
select winner};
var q = from upWinnerPair in q1
select new RankingDTO
{
UserId = upWinnerPair.up.UserID,
FirstName = upWinnerPair.up.FirstName,
LastName = upWinnerPair.up.LastName,
LastWinnerDate = /* Here you will have more simple and less repeatable code
using winners collection from "upWinnerPair.winners"*/
The query itself is pretty simple: just a main outer query and a series of subselects to retrieve actual column data. While it's not the most efficient means of querying the data you're after (joins and using windowing functions will likely get you better performance), it's the only real way to represent that query using either the query or expression syntax (windowing functions in SQL have no mapping in LINQ or the LINQ-supporting extension methods).
Note that you aren't doing any actual outer joins (left or right) in your code; you're creating subqueries to retrieve the column data. It might be worth looking at the actual SQL being generated by your query. You don't specify which ORM you're using (which would determine how to examine it client-side) or which database you're using (which would determine how to examine it server-side).
If you're using the ADO.NET Entity Framework, you can cast your query to an ObjectQuery and call ToTraceString().
If you're using SQL Server, you can use SQL Server Profiler (assuming you have access to it) to view the SQL being executed, or you can run a trace manually to do the same thing.
To perform an outer join in LINQ query syntax, do this:
Assuming we have two sources alpha and beta, each having a common Id property, you can select from alpha and perform a left join on beta in this way:
from a in alpha
join btemp in beta on a.Id equals btemp.Id into bleft
from b in bleft.DefaultIfEmpty()
select new { IdA = a.Id, IdB = b.Id }
Admittedly, the syntax is a little oblique. Nonetheless, it works and will be translated into something like this in SQL:
select
a.Id as IdA,
b.Id as Idb
from alpha a
left join beta b on a.Id = b.Id
It looks fine to me, though I could see why the multiple sub-queries could trigger inefficiency worries in the eyes of a coder.
Take a look at what SQL is produced though (I'm guessing you're running this against a database source from your saying "table" above), before you start worrying about that. The query providers can be pretty good at producing nice efficient SQL that in turn produces a good underlying database query, and if that's happening, then happy days (it will also give you another view on being sure of the correctness).
Sorry about the vague title, not sure what verbage I should be using. I have a query similar to this (re-worked to save space):
SELECT
*
FROM
Publishers p
INNER JOIN Authors a
ON p.AuthorID = a.AuthorID
INNER JOIN Books b
ON a.BookID = b.BookID
WHERE
p.PublisherName = 'Foo'
ORDER BY
b.PublicationDate DESC
I tried to re-write it as such:
var query =
from publisher in ctx.Publishers
from author in publisher.Authors
from books in author.Books
...
but got the following error:
Error 1 An expression of type 'Models.Books' is not allowed in a
subsequent from clause in a query expression with source type
'System.Linq.IQueryable<AnonymousType#1>'. Type inference failed in the
call to 'SelectMany'.
I can re-write the LINQ to make it work by just joining the tables, as I would in SQL, but I thought I could accomplish what I want to do by their relationships - I'm just a bit confused why I can get publisher.Authors, but not author.Books.
Check that you have a relationship in your DB from Authors to Books.
Try this...
var result = (from pItem in ctx.Publishers
join aItem in ctx.Authors on pItem.AuthorId equals aItem.AuthorId
join bItem in ctx.Books on pItem.BookId equals bItem.BookId
where pItem.PublisherName== "Foo"
select new {
// Fields you want to select
}
).ToList();
i don't know exact relationship of the tables but you can an idea from this one.
var result = from R in db.Clients.Where(clientWhere)
join RA in db.ClientAgencies on R.SysID equals RA.SysID
join A in db.Agencies.Where(agencyWhere) on RA.AgencyID equals A.AgencyID
join AC in db.AdCommittees on A.AgencyID equals AC.AgencyID into temp
from x in temp.DefaultIfEmpty().Distinct()
select new {R,RA,x};
If user enters CommitteeID this is what I do, but I feel there has to be a better way.
var query = (from R in result
where R.x.CommitteeID == params.CommitteeID
select R.R).Distinct();
return query;
Is there a better way?
How are you using the data. The joins could be hurting you depending on what you're trying to achieve (which is very difficult for us to view without context of your data structures).
I can't fault the linq other than to say that you appear to have a log of data being joined which you may or may not need.
The other problem I have is that you will execute the query when you call DefaultIfEmpty(). This means to do your filter you may hit the database again to calculate it's result.
Could you provide some info on your DB Schema and what you are trying to get from your query?
If you're not using your intermediate query for anything else, I would flip it (filter by committeeID first):
Client GetCommitteeClient(int committeeID)
{
return (
from AC in db.AdCommittees
where AC.CommitteeID == committeeID
join A in db.Agencies.Where(agencyWhere) on AC.AgencyID equals A.AgencyID
join RA in db.ClientAgencies on A.AgencyID equals RA.AgencyID
join R in db.Clients.Where(clientWhere) on RA.SysID equals R.SysID
select R
).SingleOrDefault();
}