C# - LINQ To SQL Join 3 Tables And Select Multiple Columns And Also Using Sum

Aug 19, 2010

I have three tables Student, TimeSheet and TimeRecord.

Talbe columns:
Student : StudentId, FirstName,
LastName
TimeSheet: TimeSheetId,StudentId, IsActive

[Code].....

View 4 Replies


ADVERTISEMENT

C# - LINQ To SQL Join Two Tables To Select Parent Table Twice Based On Two Different Columns From Child Table?

Aug 23, 2010

I have two tables Employees and CafeLogs. Some employees can be cashiers and also customers at the Cafe shop.

Table structures:

Employees: EmployeeId(PK) , FirstName, LastName
CafeLogs: LogId (PK), CashierId, EmployeeId, Value, => CashierId and EmployeeId are the data from column EmployeeId of Empoyee table

Table relationship:

Employees 1:N CafeLogs (CashierId (FK))

[code]....

Right now I know how to select only LogId, Employee's name, and , Value, not with Cashier name yet.

Dim query = From log In db.CafeLogs _
Join emp In db.Employees On emp.EmployeeId Equals log.EmployeeId _
Select log.LogId, emp.FirsName, emp.LastName, log.Value

View 1 Replies

LINQ Query - Join Tables On Nullable Columns

Apr 17, 2011

How to JOIN tables on nullable columns? I have following LINQ-query, RMA.fiCharge can be NULL:
Dim query = From charge In Services.dsERP.ERP_Charge _
Join rma In Services.dsRMA.RMA _
On charge.idCharge Equals rma.fiCharge _
Where rma.IMEI = imei
Select charge.idCharge

I get a "Conversion from type 'DBNull' to type 'Integer' is not valid" in query.ToArray():
Dim filter = _
String.Format(Services.dsERP.ERP_Charge.idChargeColumn.ColumnName & " IN({0})", String.Join(",", query.ToArray))
So I could append a WHERE RMA.fiCharge IS NOT NULL in the query. But how to do that in LINQ or is there another option?

The problem was that the DataSet does not support Nullable-Types but generates an InvalidCastException if you query any NULL-Values on an integer-column. The modified LINQ-query from dahlbyk works with little modification. The DataSet generates a boolean-property for every column with AllowDbNull=True, in this case IsfiChargeNull.

Dim query = From charge In Services.dsERP.ERP_Charge _
Join rma In (From rma In Services.dsRMA.RMA _
Where Not rma.IsfiChargeNull
Select rma)
On charge.idCharge Equals rma.fiCharge _
Where rma.IMEI = imei
Select charge.idCharge

View 2 Replies

Linq To Datarow, Select Multiple Columns As Distinct?

Apr 16, 2010

basically i'm trying to reproduce the following mssql query as LINQ

SELECT DISTINCT [TABLENAME], [COLUMNNAME] FROM [DATATABLE]

the closest i've got is

Dim query = (From row As DataRow In ds.Tables("DATATABLE").Rows _
Select row("COLUMNNAME") ,row("TABLENAME").Distinct

when i do the above i get the error

Range variable name can be inferred only from a simple or qualified name with no arguments.

i was sort of expecting it to return a collection that i could then iterate through and perform actions for each entry. maybe a datarow collection?

As a complete LINQ newb, i'm not sure what i'm missing.
i've tried variations on

Select new with { row("COLUMNNAME") ,row("TABLENAME")}

and get:

Anonymous type member name can be inferred only from a simple or qualified name with no arguments.

to get around this i've tried

Dim query = From r In ds.Tables("DATATABLE").AsEnumerable _
Select New String(1) {r("TABLENAME"), r("COLUMNNAME")} Distinct

however it doesn't seem to be doing the distinct thing properly.

View 3 Replies

Asp.net - Select Distinct Rows From A Datatable With Criteria Involving Multiple Columns Using LINQ

Mar 9, 2012

I have a datatable as shown in the figure. Let me explain my required based on this image. I have 7 rows of data. The rows 1 and 2 contains columns till UnitSqcNo same. I want only row 3 among the two. In general I want select all the rows with distinct model, unittype, unit and rest with greater CompId. ie the table should look like

View 1 Replies

LINQ To SQL And Join Two Tables With OR Clause

Apr 23, 2009

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

View 2 Replies

Can't Use A Where Clause On Both Tables In A LINQ Group Join?

Jun 7, 2011

Here's what I want to do:

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?

View 1 Replies

Join - Added Three Tables To A LINQ To SQL Class - Then Connected To The Data Sources

Jan 23, 2012

I have three tables: BOOKS(BookID, Title, Author) CLASSES(ClassID, Title, MajorID,BookID) and MAJORS(MajorID, Description). I added these three tables to a LINQ to SQL class (UBooks.dbml) and then connected to the data sources. Then declared DataContext.

Using LINQ, my goal is to display all books in a grid which I have done with:

Dim allBooks = From Books In db.Books _
Order By Books.BookID _
Select Books

Me.BookBindingSource.DataSource = allBooks

Next I need to display all majors in a listbox. I would like the description to be shown however I am only getting the majorID to display with the code

lstMajors.DataSource = db.Majors

I have tried db.Majors.Description, however I am told then that Description is not a member of the LINQ table. and my final goal is to display all the books for whichever Major is selected in another data grid. This is what I am primarily concerned with right now. When using the SQLClient classes, I was able to create a string joining the tables (also had the description properly showing in the listbox, but that is of little importance right now to me). In the video tutorials I was able to watch whenever the tables were dragged from the database into the OR designer of the LINQtoSQL.dbml class file all of the associations were already there and the narrator only really had to do some drag and drop. Not only is drag and drop not working without these associations, but I'd much rather learn the code behind it.

View 4 Replies

Access - JOIN Two Tables With Multiple WHERE Conditions

Jun 21, 2010

I have two tables 1) tblRequests and 2.) tblMainTags. The Fields in tblRequests are Tag_Request_No, Employee_ID , Accepted, Accepted_Date, and Accepted_Time. The Fields in tblMaintags are Tag_Request_No, Tag_ID, Completed, ... The fields 'Accepted' and 'Completed' are set to YES/NO.

[Code]...

View 5 Replies

Join Multiple Tables In Diffrent And Same Database?

Sep 26, 2010

I have a problem i need to join two table from different sql servers and as a test i have tried to get data from two table but i realizethe adapter can have only one connection statement as argument how do i get records from two table from diffrent database

Please see my code
Dim adapter As SqlDataAdapter
Dim ds As New DataSet

[code].....

View 6 Replies

Equivalent To JOIN Query With Dataset Multiple Tables?

Dec 21, 2011

How to Query multiple tables in a dataset to form single consolidated table without using any external database. I know this can be done using 'JOIN' in SQl.

Now my condition is I have multiple tables filled with data in a dataset and each table is interrelated with a common 'column'. For example ,

Table 1
ID
Name
1

[Code].....

Here I mentioned only two tables but in my case there are many tables. I need a generic answer for this dynamic query .

View 8 Replies

VS 2005 Load Multiple Tables Into A Recordset Using The Join Command?

Jun 3, 2009

I've found alot of examples for add/edit/delete a single table. In VB6 ADO you could load multiple tables into a recordset using the join command. Then manipulate or modify the data.

I've found how to retreive multiple tables like,

Da = New OleDb.OleDbDataAdapter("Select groups.groupid,groups.userid,lots.groupid,lots.lotid from groups inner join lots on groups.groupid=lots.groupid order by groups.groupid asc", DB) But the only way I have found to update is to use seperate Update commands for each table.

View 6 Replies

Join With Multiple (OR) Conditions In LINQ To SQL?

Jul 8, 2010

How would I perform this SQL query

Select Distinct s.*
from #ScopeIDs x
Join Scopes s on s.ScopeID=x.ScopeID or x.ScopeID is null

in LINQ to SQL? (This query would return all Scopes whose ScopeID is present in #ScopeIDs, unless one of the entries in #ScopeIDs is null, in which case it returns all Scopes).

A "literal" translation doesn't work, since LINQ doesn't support joining with multiple conditions - code along these lines ...

From x in ScopeIDs
Join s in Scopes on s.ScopeID equals x.ScopeID or x.ScopeID equals nothing
Distinct Select s
... doesn't compile.

View 1 Replies

Join Multiple Datatables Using LINQ To Dataset?

Feb 8, 2012

I have been searching for quite a while about joining multiple datatables via LINQ to dataset (When i say multiple, i don't mean just 2!!!), and it seems there aren't lot of examples in the net. I have seen examples of joining two datatables, done that, no problem there. Now i want to join three datatables. And there's nothing i can find out there.For example i have a 3 datatables:

PERSON (columns: person_id, name, gender_code, ethnic_code)
GENDER (columns: gender_code, gender_description)
ETHNICITY (cols: ethnic_code, ethnic_description)

[code].....

View 1 Replies

LINQ: "Group Join" Functionality Joining Three Tables

Jul 21, 2010

I'm working on becoming familiar with LINQ, and getting my head around the syntax and usage.

[Code]...

View 1 Replies

Dataset - Multiple Tables - Multiple Columns

Sep 18, 2009

I have a small project i am doing for work to compare our website catalogue to our actual inventory in our financial software. To do this, i have exported the online catalogue as a delimited text file using "^" as the delimiter. I then want to go into our Accpac data a find out if all the items are still active, the current price and the stock on hand.

[Code]...

View 6 Replies

DataGridView With Columns From Multiple Tables?

Jun 10, 2009

I have 3 related tables in a DataSet - Customers, Products and Orders.I am trying to create an "editable" DataGridView which, ideally, will contain columns from all the tables. I have tried creating the joins in the TableAdapter SQL, but this results in a read-only data grid.

Customers and Orders are joined in a 1:M relationship by CUSTID.

Products and Orders are joined in a 1:M relationship by PRDID.

When the user adds a new Order record they will key the ORDERID, CUSTID, PRDID and QTY.I would like the DataGridView to display the related CUSNAM and PRDDES as soon as the user has keyed the Order record.The data must be displayed on a single data grid row. I am not interested in drill down or multiple data grids.My data looks like this:

Orders: ORDERID, CUSTID, PRDID, QTY

Products: PRDID, PRDDES

Customers: CUSTID, CUSNAM

The data grid should look like this:

ORDERID, CUSTID, CUSDES, PRDID, PRDDES, QTY

My SQL would look like this:

SELECT Orders.ORDERID, Orders.CUSTID, Customers.CUSNAME, Orders.PRDID, Products.PRDDES, Orders.QTY

FROM (ORDERS

INNER JOIN CUSTOMERS ON Orders.CUSTID = Customers.CUSTID)

INNER JOIN PRODUCTS ON Orders.PRDID = Products.PRDID;

View 1 Replies

Relation For Multiple Columns Between Two Tables?

Jan 8, 2010

<vb.net 2008>
Table : MST_COMPANY / EMP_MASTER
Column : COMPANY_ID / LOCATION_ID

How do I add relations for two colums between two tables? I tried below way but it does not work.
Is there any other way?

Dim relCompanyEmp1 As DataRelation = ds.Relations.Add("relSectionEmp", ds.Tables("MST_COMPANY").Columns("COMPANY_ID"), ds.Tables("EMP_MASTER").Columns("COMPANY_ID"))
Dim relCompanyEmp2 As DataRelation = ds.Relations.Add("relSectionEmp", ds.Tables("MST_COMPANY").Columns("LOCATION_ID"), ds.Tables("EMP_MASTER").Columns("LOCATION_ID"))

[Code]...

View 5 Replies

Use SQL To Search Multiple Tables And Columns?

Aug 23, 2009

Im making a search function for an application and they need to be able to search by any value in the DB in any of the three tables. Im wondering the best way to go about this. 2 of the 3 tables have the same columns while the last one is totally different. Below is what I kinda "thought" itd look like but no.

"SELECT * FROM cases, opencases, staff WHERE Crime ='" & txtsearch.Text.ToString & "'"

I need to query the results the user can search for anyterm and if it matches something in the columns it return it to the user. Im wondering if the best way to go about this is to maybe query all the tables and then put all the matching records in a seperate table and the dgv look at that table or how to exactly go about it.

View 1 Replies

Select To Multiple Sql Tables Using Select Query?

Jul 23, 2011

I want to select to multiple sql tables using select query in vb.net..I have 2columns in sql table..I have tried this query.. But i'm getting error.

TextBox11.Text = Val(27)
cmd = New SqlCommand("SELECT outside,power FROM vijay21 INNER JOIN vijay22 ON vijay21.outside=vijay22.outside WHERE outside BETWEEN " & Val(TextBox11.Text) & " AND " &

[code].....

View 4 Replies

Inner Join - Join Two Tables,'Employee' And 'Dispatch'

May 17, 2012

Iwant to join two tables,'Employee' and 'Dispatch'. Dispatch has column 'DispatcherID' and 'TechnicianID' which are both foregn keys to EmployeeID in Employee table.I want to join these two tables using EmployeeID so that i can obtain the matching name to each id.but it only works when i make a single join to either DispatcherID or TechnicianID and not for both.

[code]

select Employee.firstname+' '+Employee,secondname as Technician,Employee.firstname+' '+Employee.secondname as Dispatcher from Dispatch inner join Employee on Dispatch.TechnicianID=Employee.EmployeeID inner join Employee on

[CODE]...

View 12 Replies

VS 2010 : Display All Selected Columns From Multiple Joined Tables?

May 11, 2011

I have multiple tables that I need to pull and display data from. I have created a new query in the TableAdapter of one table to pull data from related tables based on a parameter. In the Query Designer I can run my query and see all of the columns requested in my SELECT statement, however when I bind this table to a DataGridView and call the new query, it only returns the original columns from Table1.How do I see all of the columns I selected in my query?

View 3 Replies

Linq - Group By Multiple Columns?

Dec 6, 2011

I have a list of attachments that I need to group by clientCLID and EmailAddress. From this grouped list I only need a list of clientCLIDs. After fiddling for a while I've managed to get it to work as follows:

[Code]...

View 1 Replies

Update Tables Using Bindingnavigator Save Button From Join Tables

Oct 29, 2010

In my datagridview I was fill in using join tables (table1 = pr_employees, table2 = pr_employee_deduction). My problem now is during save button I want to update records from table2 only.[code]

View 3 Replies

LINQ To SQL Grouping Multiple Columns With A Distinct Row

Aug 9, 2010

I have the following table structure. I want to select distinct CustomerId and CustomerName, TotalCost.[code]

View 2 Replies

Group Joins With Multiple Tables Converting SQL To Linq

Mar 7, 2011

Can anyone help me by translating this SQL Statement to Linq? [code]

View 1 Replies

Iterate Through LINQ Query - Results From Multiple Tables

Dec 7, 2010

I have a VB .Net linq query that I want to return values from two tables. I currently have this:
Dim query = (From c In db.Client _
Join u In db.Users _
On u.UserID Equals c.UserID _
Where (c.ClientID = 1)
Select c, u).ToList
query (System.Collections.Generic.List(Of )) returns several rows as expected each item containing a c and a u.
How do I iterate through the queries collection?

View 1 Replies

C# - Joint Query In Linq To SQL To Select All Records Even There Are Some Null In The Columns Of Foreign Keys?

Feb 2, 2011

I'd like to take all suggestion either in C# or VB.NET.I have a DB diagram like the image below. I also include the database script here [URL]In the Students table, CountryId and RoomId column are allowed null. Because some records do not have info about room and country yet.Also, some students do not have essays.I'm doing a joint query with all tables. I want to select all students to project the result like this:Wanted query result.

Here's my current query that gives the result like the image below:

Dim db As New DBDataContext
Dim query = From st In db.Students _
Join c In db.Countries On c.Id Equals st.Id _
Join r In db.Rooms On r.Id Equals st.RoomId _

[code].....

current query result I got only one result back because I have (2) William NoMan record in every table. But I don't get anything about others, like (3) Sync Master who has everything but RoomId.What do I need to modify the query above so it will give me all students like in the wanted query image above?

View 2 Replies

Linq - Order By Multiple Columns Using Lambda Expressions

Nov 16, 2009

I'm still trying to get my head around the whole "Lambda Expressions" thing.

Can anyone here give me an example ordering by multiple columns using VB.Net and Linq-to-SQL using a lambda expression?

Here is my existing code, which returns an ordered list using a single-column to order the results:

Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder).ToList

Note: The WebCategory object has a child WebPage object (based on a foreign key). I'd like to order by WebPage.DisplayOrder first, then by WebCategory.DisplayOrder.

I tried chaining the order bys, like below, and though it compiled and ran, it didn't seem to return the data in the order I wanted.

Return _dbContext.WebCategories.OrderBy(Function(c As WebCategory) c.DisplayOrder).OrderBy(Function(c As WebCategory) c.WebPage.DisplayOrder).ToList

View 2 Replies

SQL SELECT With Multiple Tables To Datatable/DataView Get Table Names

Feb 21, 2011

For my app users can enter a SELECT statement themselves. This can be any select statement at all, it will be mainly used for creating a quick view e.g. SELECT * from table1 LEFT OUTER JOIN table2 on table1.id = table2.id.

Whatever this select statement maybe I load it into a datatable (after checking for no nasty stuff of course) in vb.net. I want to know the table names so I can query the database again for validation purposes on things like datatypes etc.

da.SelectCommand = New SqlCommand(sqlStatement, tempDB.Connection)
da.MissingSchemaAction = MissingSchemaAction.AddWithKey
dt = New DataTable
da.Fill(dt)

View 3 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved