I have the following scenario I need to accomplish via Linq to SQL:
I have a table called JOBS that contains these two columns:
JobID
JobName
I have another table called JOBREFS that contains these two columns:
JobID
JobRefID
I have the following query (I already have the JOBS.JobID)
Select JobRefID from JOBREFS where JOBREFS.JobID = JOBS.JobID
Then I need to do THIS query:
Select JobName from JOBS where JOBS.JobID = JOBREFS.JobRefID
I know I can do this in two queries, but thought there might be a way to get the JobName that is associated with the JobRefID in another table.
Hope this makes sense.
If the navigation properties are correct in your models, you can just use those navigation properties instead of joins. Some examples are here:
http://coding.abel.nu/2012/06/dont-use-linqs-join-navigate/
Related
I've three tables
Investigators: id, name, first name
Articles: id, name, date
ArticlesInvestigators: id_Investigator, id_Articles, order
I want to get only all the investigators from the Investigators table to have one article published:
In SQL it would look like:
SELECT * FROM Investigators i, ArticlesInvestigators a
WHERE i.id = a.id_Articles
But how shall be in LINQ and lambda? Without join because only want the results of investigators table.
I don't know if i understand your question or not but try this way and tell us if it work or not :
1) you need to make FOREIGN KEY between your tables
2) do you query in C#
3) then you can get you data using the relation between your tables
I've been trying to grow my EF understanding from just querying tables to creating Entities that match my business objects so I can code against my business objects rather than my data objects. I read articles that suggest this is possible, but all of their examples are rather trivial and involve just combining two tables. My situation is a little more complicated and I'm not sure how to proceed.
I have two tables (simplified below)
CREATE TABLE [dbo].[BarEvents]
(
[BarGUID] UNIQUEIDENTIFIER NOT NULL DEFAULT NEWSEQUENTIALID(),
[Bar] INT NULL
)
CREATE TABLE [dbo].[BarLog]
(
[BarGUID] UNIQUEIDENTIFIER NOT NULL,
[BarLogGUID] UNIQUEIDENTIFIER NOT NULL DEFAULT NEWSEQUENTIALID(),
[BarEventTime] DATETIME NOT NULL DEFAULT GETUTCDATE()
)
So if I join these tables, for a specific BarGUID, so if I had 1 Bar and 4 bar events logged, I'd have 4 rows, but what I want is just the most recent BarEventTime. So I would like to join and have just one row:
I can do this trivially in EF:
var query = barEntities.BarEvents.Where( q=> q.BarGUID = '0000-0000-0000-0000')
.Select(barEvent =>
new LogItem()
{
Bar = barEvent.Bar,
BarEventTime = barEvent.BarLog.Max(u => u.BarEventTime)
});
But from what I've read, I should be able to define a LogItem entity, and place this logic somehow in my LogItem entity, then write queries against that. My problem is I only see trivial join conditions when I'm trying to join my tables in the entity definitions. Is there a way to do this? Or a guide?
Any help would be appreciated.
Thank you.
Why don't you do the following:
Create a SQL View in the Database that does what you want
Add the view to your EF Context
Use the newly created entity that is based on the view
I'm writing a C# application and am using an Access .mdb. I have a table with email messages and a table with message relations (each email msg can be assigned to several teams of workers), so the rows in the relations table have "msgId" and "teamName" fields.
I want to to get all messages from the first table which are assigned to a specified team. I'm using the following query:
"SELECT * FROM Mails INNER JOIN MailAssignments ON Mails.msgId = MailAssignments.msgId"
But it doesn't return the msgId for me, I guess, because the tables are joined on this field, but then I
m not able to identify messages in my C# code.
How can I make the query return the msgId for me?
It is enough specify the fields name in the selection, or add the table name where you want to get all the fields, try with this selection list :
SELECT Mails.*
FROM Mails INNER JOIN MailAssignments
ON Mails.msgId = MailAssignments.msgId
It should appear twice in the resultset, for Mails.msgId and MailAssignments.msgId respectively. However, you should not expect two columns named msgId. Rather, the DBMS should disambiguate the columns. This is a requirement of Standards SQL, BTW.
IIRC Access will rename both columns in order to disambiguate them. This would explain why there is no column named msgId in the result.
In SQL I have 2 tables.
Sport Athlete
SportId AthleteId
SportName AthleteName
Their relation is many to many. So there is a third table that join them.
AthleteSport
AthleteId
SprortId
If i create an entity data model using the wizard the third table is disapeared and only creates the 2 main tables with the many to many relation.
how can I perform a query to find out what kind of sports athlete 'A' does? How to change them or add a new sport?
I want to use linq and c#.
Thank you.
In your Sport entity, there will be a so called "navigation property" Athletes that contains all Athletes that belong to that Sport instance.
The same is true the other way around.
Can't you do A.Sports and get that list?
I have a medical database that keeps different types of data on patients: examinations, lab results, x-rays... each type of record exists in a separate table. I need to present this data on one table to show the patient's history with a particular clinic.
My question: what is the best way to do it? Should I do a SELECT from each table where the patient ID matches, order them by date, and then keep them in some artificial list-like structure (ordered by date)? Or is there a better way of doing this?
I'm using WPF and SQL Server 2008 for this app.
As others have said, JOIN is the way you'd normally do this. However, if there are multiple rows in one table for a patient then there's a chance you'll get data in some columns repeated across multiple rows, which often you don't want. In that case it's sometimes easier to use UNION or UNION ALL.
Let's say you have two tables, examinations and xrays, each with a PatientID, a Date and some extra details. You could combine them like this:
SELECT PatientID, ExamDate [Date], ExamResults [Details]
FROM examinations
WHERE PatientID = #patient
UNION ALL
SELECT PatientID, XrayDate [Date], XrayComments [Details]
FROM xrays
WHERE PatientID = #patient
Now you have one big result set with PatientID, Date and Details columns. I've found this handy for "merging" multiple tables with similar, but not identical, data.
If this is something you're going to be doing often, I'd be tempted to create a denormalized view on all of patient data (join the appropriate tables) and index the appropriate column(s) in the view. Then use the appropriate method (stored procedure, etc) to retrieve the data for a passed-in patientID.
Use a JOIN to get data from several tables.
You can use a join (can't remember which type exactly) to get all the records from each table for a specific patient. The way this works depends on your database design.
I'd do it with separate SELECT statements, since a simple JOIN probably won't do due to the fact that some tables might have more than 1 row for the patient.
So I would retrieve multiple result-sets in a simple DataSet, add a DalaRelation, cache the object and query it down the line (by date, by exam type, subsets, ...)
The main point is that you have all the data handy, even cached if needed, in a structure which is easily queried and filtered.