.net - Linq-to-Entities: LEFT OUTER JOIN With WHERE Clause And Projection?
Oct 18, 2010
how to translate a simple SQL LEFT OUTER JOIN with a two condition where clause into a working Linq-to-Entities query. There are only two tables. I need values for all rows from Table1, regardless of matches in Table2, but the WHERE clause uses fields from Table2. In SQL, the two parameters would be Table2WhereColumn1 and Table2WhereColumn2, and the query (which works) looks like this:
I've tried using Group Join with DefaultIfEmpty(), as well as an implicit join (without the actual Join keyword), and I only get rows for items that have values in Table2. I'm sure this won't help, but here's an example of the Linq I've been trying that doesn't work:
Public Shared Function GetProfilePreferencesForCedent(ByVal dc As EntityContext, _
ByVal where1 As Int32, _
ByVal where2 As Int32) _
I ultimately what I needed is generic function which would take two datatable and and 2 tablekeys and return Joined datatable. So here is my first step to solve it.
How Can I write Linq example of following T-SQL example in VB?
SELECT * FROM Table1 LEFT OUTER JOIN Table2 ON Table1.key = Table2.key
I cannot get this to work with LINQ to SQL vb.net?
SELECT a.FLD_ID, a.FLD_SUBJECT, a.FLD_GROUP, a.FLD_SUBMITTED, a.FLD_LASTACTION, a.FLD_CLOSED FROM TBL_WSS_TT_TICKET a LEFT OUTER JOIN TBL_WSS_TT_ALLOW b ON a.FLD_ID = b.FLD_TICKET_REF WHERE (a.FLD_USER = 'user') OR (b.FLD_USER = 'user')
I've got what I think is a working left outer join linq query but I'm having problems with the select because of null values in the right hand side of the join.[code]I want to return all of e and one column from c called tClassCode. I was wondering what the syntax would be. As you can see I'm using vb.net.[code]If i remove the c.tClassCode from the select the query runs without error. So i though perhaps i needed to do a select new but i don't think i was doing that correctly either.
I've looked all around and spent way to long trying to convert this SQL statement into a Linq statement in VB. I'm sure it would be a good example for others out there - the statement is trying to pull products that have a many-to-many relationship with product categories, and the categories have a hierarchy of parents/children.
Here is the query I am trying to convert:
SELECT P.ProductID, P.ProductName, P.ProductSlug, P.PartNumber FROM Products AS P INNER JOIN Products_Categories AS PC ON PC.ProductID = P.ProductID
[code]....
I can get up to the point where I am trying to say "WHERE ... (P_Cats.Parent = 9)" but can't figure that part out.
i'm having troubles with a linq-to-sql statement and getting a left outer join to work. here is a sample of two tables i'm trying to join and my code that i've wrote.
Table1 Table2 f1 f2 f3 f4 fID f1 f2 f3 f4 val1 val2 val3 val4 1 val1 val2 val3 val4
[code]....
Instead I'm returning ALL values from table 1. I need to return all values from the left outer join where tbl2.fID is null.
I have two tables, a LP_task table and an lp_Update table. I want a complete list of tasks and only updates that were posted during a specific date range. LINQ doesn't seem to support any other join criteria but 'equals'or each task. I want all tasks (left table) even if they don't have an update. (Left Outer Join)
Dim TasksData = (From t In db.LP_Tasks _ Group Join up In db.LP_Updates On t.ID Equals up.TaskID Into upds = Group _ From u In upds.DefaultIfEmpty _
Im trying to use LINQ to query Objets. I'm doing the following:
Dim myList As Generic.List(Of MyItem) = (From ThisItem In LinqToSqlObject.Items _ Join Folder In LinqToSqlObject.Folders _ On Folder.Id Equals Item.Id _
[Code]....
This however will not return any item that has a ParentItemId of null. I am trying to do a left join so as to return all "Item" regardless of whether it has a parent or not. I am aware that this is feasible in C# by adding an "into X" on the join, and selecting from X.DefaultIfEmpty(), this however does not appear to work in VB.Net.
Given two tables, customer and orders, how would one do a linq query to entities to find any customers with open invoices started before a certain date?
Let's say I have Plans and Documents Dim myPlans = _context.Plans.Where(predicate1) Dim myDocuments = _context.Documents.Where(predicate2)
I have structured the where clause for each using PredicateBuilder. So, myPlans and myDocuments have a correct SQL statement. What I'd like to do is join these two tables into one linq statement. The problem I'm having is that, by default the AND condition is joining the where clauses.
myPlans Where clause : (p.name like "%test%" AND p.name like "%bed%") OR (p.description like "%test%" AND p.description like "%bed%") myDocuments Where clause : (d.name like "%test%" AND d.name like "%bed%") OR (d.description like "%test%" AND d.description like "%bed%")
When I combine the two the desired result Where clause is: Where (d.ID = p.ID) AND (myplans where clause above) OR (mydocument where clause above). Meaning, I'd like the two where clauses in each of the tables to be "or" instead of "And".
The current result where clause is: Where (d.ID = p.ID) AND (myplans where clause above) AND (mydocument where clause above). Meaning, I'd like the two where clauses in each of the tables to be "or" instead of "And".
I'm forming the statement like this: Dim test = From d in myDocuments _ Join p in MyPlans on d.ID Equals p.ID _ Select d.Name, p.Name
Dim queryX = From m In db.Master Where m.Field = value Group Join d In db.Detail On m.Id Equals d.MasterId Into Group Where d.Field = value
In English, I want to join the master and detail tables, specifying conditions on each. But this causes the following compiler error:
"Name 'd' is either not declared or not in the current scope."
It works if I put this same condition in functional form:
Group Join d In db.Detail.Where(Function(x) x.Field = value)
but I think this is more typing, harder to understand, and introduces that irritating dummy variable. I really would prefer to use the query comprehension syntax. Is there a way to accomplish this?
I can't figure out that linq to entity query syntax. My problem is that if the value of the Calls table is null then noting comes up, I want to make something like a left join to get 'all' rows from the Calls table.I tried to group it but I can't figure out the correct way to write it.
Dim TicketQuery As ObjectQuery = From c In EnData.Customer _ Join t In EnData.Calls On t.CustomerID Equals c.CustomerID _ Join Status In EnData.Lists On t.Status Equals Status.ListValue _
i think i have not represented my question correctly here My LEFT OUTER JOIN MSDN reference is here to visualize my problem in access databaseTABLE "T1"1234567TABLE "T2"1,sunday2,monday i need output as 1,sunday2,monday34567 i need it to done through LINQso far i did is here
Dim RIGHT_table As DataTable = ds1.Tables("t1") Dim LEFT_table As DataTable = ds2.Tables("T2") Dim OutPut = From LEFTsource In LEFT_table.AsEnumerable(), RIGHTsource In RIGHT_table.AsEnumerable() _
I have two UNTYPED datatables: "Shelfs" and "Books". Data came from different databases.
I must create a "left join" relationship because I want a list of ALL shelfs and books (if they have any).
Dim dset As New DataSet dset.Tables.Add(dtShelfs) dset.Tables.Add(dtBooks)
[Code].....
I spent hours googling around, but all examples I found were only applicable to strongly typed dataSets, and how to build queries (not to get the data)
I could solve this the "easy" way: by looping both datatables and sending the rows to a third one, but I want to do this the "right" way and, of course... LINQ exists to make things easier and I don't know how to use it
i am having 2 tables one table stores the WEEK-days another table stores the WEEK-days + other fields.i need the LINQ query to return all WEEK-days + other fields just like SQL LEFT JOIN query so far i did is [code]....
The query works but only retrieve the joined rows, i want to retrieve all rows in the first datatable.My current query:
vb.net Dim q = From regE In (From registoE In _dtRegistosAEnviar.AsEnumerable Group registoE By colaborador = registoE.Field(Of String)("Colaborador") Into grupoE = Group Select New With {
I'm having a hard time joining 2 datatables and have the joined datatable as result. First datatable (labels) holds data including a printerid. Second datatable (printers) holds printer references (id > unc). I would like to have as endresult (joined) a datatable with all data from the first datatable with the field (unc) of the second datatable. [Code]
I am new to ado.net and I am trying to learn capabilities as much as get this particular task done.Let me set the stage for my question.My goal is to load up a dataset, write out an XML, transfer the file to another machine, read the XML back into a data set, load up the local tables, find missing records from the local database and add them.These tables are for employees. There is the 'Employee' master, "Employee Job" the employee job code, and "Employee Hours", the employee time punches.I thought I could treat a dataset as a database and do SQL queries against it.For example to find missing Employee , my thought was to do a outer join on employeeID and look for null in the second table.Something like:
Basically what I'm having to do is create a program that takes a list of CaseIDs and compares them to a table on a remote SQL server. However, the table holding the CaseIDs on the remote server has nearly 120,000 records.
Currently my plan is to query all records on the remote server, save the query and the current list to tables in an Access DB file and then run an outer join to see which CaseIDs have no matching records on the remote server.
I believe this will be a much slower process than I would like. If I could load both queries into arrays or lists in VB and then compare them (therefore, not having to write 120,000 records to a DB file), it would be much faster.
I have a listbox on my xaml form that I bound to a List(Of MyType) property. I populated this list like so:
Dim fields As List(Of CheckableFields) = New List(Of CheckableFields) Using context As ITIPEntities = New ITIPEntities() Try[code]....
Now I'm at the point where the user selects the fields they want included in a report and I need to iterate over the required fields. This is my linq query:
For Each checkedField In _requiredFields If checkedField.IsChecked Then If checkedField.FieldData IsNot Nothing AndAlso checkedField.FieldData.Trim IsNot String.Empty Then[code].....
I am using/creating a DataTable so the "enforceConstrains" property is not avilable for DataTable.Error message: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Windows Form Load Event:
Private Sub Expenses_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load expensesGV.DataSource = listExpenses() expensesGV.Columns(0).Visible = False End Sub
The pattern I'm trying to avoid is checking if a string (normally a control's text value) is null/empty, and if it is, comparing it using Contains to a field in my data. Obviously the field isn't hard-coded into my extension, neither is the object type.What I've got works perfectly in Linq to Objects, but I get the generic run-time error "LINQ to Entities does not recognize the method 'System.String Invoke(GenericQueryHelper.Customer)' method, and this method cannot be translated into a store expression." when using an entity framework model.
Here's what I have:
<System.Runtime.CompilerServices.Extension()> Public Function CompareAndFilter(Of T)(source As System.Linq.IQueryable(Of T), expressionField As System.Linq.Expressions.Expression(Of System.Func(Of T, String)), compareTo As String)
[code]....
I want my usage to look something like this:
Dim results = repository.Customers.CompareAndFilter(Function(c) c.FirstName, searchText)
I do need to get this running against a SQL database really, as it is filtering results, so I don't want to be doing that in memory.
I am trying to accomplish the following: SELECT Table1.prod_code, SUM(Table1.prod_bal) AS TotalProdBalance FROM Table1 LEFT OUTER JOIN Table2 ON Table1.prod_code = Table2.prod_code WHERE Table2.prod_code IS NULL GROUP BY Table1.prod_code HAVING (SUM(Table1.prod_bal) <> 0) How to translate this to Linq using VB.net syntax?