Linq query accross joined tables in EF - linq

hello, can you help me how to write Linq query (using Entity Framework) for the following requirements:
I have tables:
User(ID, Name),
Checklist(ID, Name, UserID(NOT NULL))
Job(ID, Name, UserID(NOT NULL))
Task(ID, Name, JobID(NULLABLE), UserID(NULLABLE), ChecklistID(NULLABLE)),
In the Task table there is always only one of foreign keys filled (others are NULL):
Task data example:
ID Name JobID UserID ChecklistID
1 T1 1 NULL NULL
2 T2 NULL 1 NULL
3 T3 NULL NULL 1
...
I want to select all tasks for the user based on the following rules:
1. all tasks belonging to user (UserID is filled)
2. all tasks which are related to job (JobID is filled) and Job is owned by the user
3. all tasks which are related to Checklist (ChecklistID is filled) and Checklist is owned by the user
4. ID of the user is input parameter
I want to get result in one Linq query. I'm beginner in Linq and I have no idea how to do it correctly.
thanks a lot for your help.

This appears to be what you're trying to get. You may have to add in "DataContext." before the table names.
var stuff = (from t in ScheduledTasks
where t.UserID == userID
|| t.CheckLists.UserID == userID
|| t.Jobs.UserID == userID
select t);

Related

Dynamics CRM 2011 Linq Left Outer Join

I am trying to get all records from an entity that do not join to another entity.
This is what I am trying to do in SQL:
SELECT * from table1
LEFT join table2
ON table1.code = table2.code
WHERE table2.code IS NULL
It results in all table1 rows that did not join to table2.
I have it working with Linq when joining on one field, but I have contact records to join on firstname, dob, and number.
I have a "staging" entity that is imported to; a workflow processes the staging records and creates contacts if they are new.
The staging entity is pretty much a copy of the real entity.
var queryable = from staging in linq.mdo_staging_contactSet
join contact in linq.ContactSet
on staging.mdo_code equals contact.mdo_code
into contactGroup
from contact in contactGroup.DefaultIfEmpty()
// all staging records are selected, even if I put a where clause here
select new Contact
{
// import sequence number is set to null if the staging contact joined to the default contact, which has in id of null
ImportSequenceNumber = (contactContactId == null) ? new int?(subImportNo) : null,
/* other fields get populated */
};
return queryable // This is all staging Contacts, the below expressions product only the new Contacts
.AsEnumerable() // Cannot use the below query on IQuerable
.Where(contact => contact.ImportSequenceNumber != null); // ImportSequenceNumber is null for existing Contacts, and not null for new Contacts
Can I do the same thing using method syntax?
Can I do the above and join on multiple fields?
The alternatives I found were worse and involved using newRecords.Except(existingRecords), but with IEnumerables; is there a better way?
You can do the same thing with method calls, but some tend to find it harder to read since there are some LAMBDA expressions in the middle. Here is an example that shows how the two are basically the same.
I've seen others ask this same questions and it boils down to choice by the developer. I personally like the LINQ approach since I also write a bunch of SQL and I can read the code easier.

Oracle SQL Query to get missing date from two joined tables

I'm trying to write a Oracle SQL query and I'm unable to get the right result.
For the tables below, I would like to first get all records from DEVICE where DEVICE.MODEL='UNITA' and for those results, give me the DEVICE.CUSTOMER_ID's who don't have a record where PROFILE.TYPE='TEST' joining both tables on CUSTOMER_ID. Any ideas on how to formulate this query?
TABLE DEVICE:
ID - sequence generated primary key (NUMBER (10))
DEVICE_NUMBER - unique (varchar)
CUSTOMER_ID (varchar)
MODEL (varchar)
TABLE PROFILE:
ID - sequence generated primary key (NUMBER (10))
CUSTOMER_ID (varchar)
TYPE (varchar)
If I understand the requirement, this should do the trick:
SELECT d.ID, d.Device_Number, d.Customer_ID, d.Model
FROM Device d
LEFT JOIN Profile p ON d.Customer_ID = p.Customer_ID
WHERE d.Model = 'UNITA'
AND (p.ID IS NULL OR p.Type = 'TEST')
It works because of the LEFT JOIN, which will make Profile.ID NULL if there's not a matching Profile row for the Customer_ID. If there is a matching row, the test for Profile.Type = 'TEST' will determine what's included.
There's a SQL Fiddle here. The Fiddle includes the Profile.ID and Profile.Type values in the results because I think they help explain things more clearly.
Addendum: Some confusion on my part over the requirements; this query may be closer to what's needed:
SELECT d.ID, d.Device_Number, d.Customer_ID, d.Model, p.id AS pid, p.type
FROM Device d
LEFT JOIN Profile p ON d.Customer_ID = p.Customer_ID AND p.Type = 'TEST'
WHERE d.Model = 'UNITA'
AND p.ID IS NULL

entity framework lazy loading null properties in child

Using entity framwork with lazy loading - Have the following question on loading related entities when the entities
are null.
Say I have two tables employee and employeedetails. Assume in the above case not all employee entries have an entry in the employeedetails table.
If I want to look up a list of Employees
(from e in objectcontext.employees
select new EmployeeEntity
{
EmpID= e.EmployeeID,
FirstName = e.FirstName,
Address = e.employeedetails.Address
}).ToList();
EmployeeEntity is the data class into which we stuff the results.
The above code breaks if even one employee in the returned list
does not have a entry in table employeedetails. This is obvious since e.employeedetails will be null for those customers who do not have a details entry
What is the best way to rewrite the above query?
Would something like this be acceptable ?
(from e in objectcontext.employees
select new EmployeeEntity
{
EmpID= e.EmployeeID,
FirstName = e.FirstName,
Address = e.employeedetails == null ? "" : e.employeedetails.Address,
}).ToList();
I am not clear on the efficiency of this above query - Would this statment do the null check at DB level?
Should I instead do an explicit include like
objectcontext.include("employeedetails")...
And then loop through the results to check for null?
Yes, this statement would indeed perform a null check in the SQL query that is generated. Most likely, it will simply be a NVL or COALESCE.
That's the way you should be doing it.

LINQ Query for fetching data from Multiple Tables

I am working in Asp.Net 4.0 C#-- MVC-3. I have one problem and don't know how to solve. I have 4 tables and want to fetch data from that tables with LINQ.
TABLES
1) Project_Master
Field Names :
project_id (pk)
project_name
company_id (FK with company_master)
company_category_id (FK with Company_Category_master)
project_status_id (FK with Project_Status_Master)
2)Company_Master
Field Names :
company_id
company_name
company_category_id (FK with Company_Category_Master)
3) Company_Category_Master
Field Names :
Company_Category_Id
Company_Category_Name
4) Project_Status_Master
Field Name :
Project_Status_Id
Project_Status_Name
Below are the fields I need to fetch..(using LINQ Query)
Company_Name
Total completed project using status id(1)=complete (where staus 1 means completed)
Total Project
Company_category_name
So, how can I fetch data with linq query??
Thanks in advance...
Try the below example:
(From lse In Me.Leases, nty In Me.Entities, psg In Me.ProductionStages, lsg In LeaseStages _
Where lse.LeaseName = leaseName _
Select lse, lsg, nty, psg).Single
or you can use below example too:
var employeesQuery = from populationTable in db.Populations
join personTable in db.Persons on populationTable.Guid equals personTable.PopulationGuid
join employeeTable in db.Employees on personTable.Guid equals employeeTable.PersonGuid
select new { populationTable, personTable, employeeTable};

Entity Framework and Link Table issue

I have a database which consists of the following:
** Table 1 **
Id (PK)
Field1
** Table 2 **
Id (PK)
Field2
** Link Table **
Table1Id (FK)
Table2Id (FK)
The problem is, I cannot access Table 2 from Table 1, even though the relationship exists in the database.
For example, the following should be possible:
var Results = from c in DataContext.Table1
where c.Table2.Field2 == "Test"
select c;
However, "c.Table2.Field2" is not available for some reason - all I get for "c.Table2." is the following (among the standard any<>, where<> et al):
RelationshipName
RelationshipSet
SourceRoleName
TargetRoleName
So obviously something is screwy somewhere, but I cannot work out what!
Both tables exist in the Entity Schema, and have a valid relationship between them.
The reason that c.Table2.Field2 is not available is that c.Table2 doesn't have a property called Field2. c.Table2 is a list of entities which have that property, not an instance of that entity. It's not clear what your intention is here, but I think you want:
var Results = from c in DataContext.Table1
where c.Table2.Any(t2 => t2.Field2 == "Test")
select c;

Resources