Entity Framework and Link Table issue - linq

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;

Related

Using query hints to use a index in an inner table

I have a query which uses the view a as follows and the query is extremely slow.
select *
from a
where a.id = 1 and a.name = 'Ann';
The view a is made up another four views b,c,d,e.
select b.id, c.name, c.age, e.town
from b,c,d,e
where c.name = b.name AND c.id = d.id AND d.name = e.name;
I have created an index on the table of c named c_test and I need to use it when executing the first query.
Is this possible?
Are you really using this deprecated 1980s join syntax? You shouldn't. Use proper explicit joins (INNER JOIN in your case).
You are joining the two tables C and D on their IDs. That should mean they are 1:1 related. If not, "ID" is a misnomer, because an ID is supposed to identify a row.
Now let's look at the access route: You have the ID from table B and the name from tables B and C. We can tell from the column name that b.id is unique and Oracle guarantees this with a unique index, if the database is set up properly.
This means the DBMS will look for the B row with ID 1, find it instantly in the index, find the row instantly in the table, see the name and see whether it matches 'Ann'.
The only thing that can be slow hence is joining C, D, and E. Joining on unique IDs is extremely fast. Joining on (non-unigue?) names is only fast, if you provide indexes on the names. I'd recommend the following indexes accordingly:
create index idx_c on c (name);
create index idx_e on e (name);
To get this faster still, use covering indexes instead:
create index idx_b on b (id, name);
create index idx_c on c (name, id, age);
create index idx_d on d (id, name);
create index idx_e on e (name, town);

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.

Linq2Entity Getting Values from reference Table

i have 3 tables
Table: A
- aID
- Text
Table: B
- bID
- Text
Table: A_B (reference table which holds both of the primary keys as foreign keys)
- aID
- bID
The Entity Framework knows that Table A_B is just a reference table and does not create it in the DBModel but keeps the references in Table A and B.
My question is how do i get the data which is in the reference table without actually having this table? When i try to access the values of Table B using the reference which is in Table A i cant get the values of the Table B Colums.
ObjectQuery<A> aTable = dbConnection.A;
var result = from data in aTable
where data.aID = '12'
select data.B; //B is the reference to table B out of table A
What i need is something like:
ObjectQuery<A> aTable = dbConnection.A;
var result = from data in aTable
where data.aID = '12'
select data.B.bID;
How do i get data out of Table B using the reference between Table A and Table B?
Using: VS 2010 Prof, .Net 4, Linq2Entity
As Gary Said, you either use First (if you want one B for each A), FirstOrDefault (if you want nulls where there is no B for A) or SelectMany (if you want all Bs for each A)
The latter can be written like this:
var result = from data in dbConnection.A
from b in data.B
select b.Id;

table subtraction challenge

I have a challenge that I haven’t overcome in the last two days using Stored Procedures and SQL 2008.
I took several approaches but must fell short.
One appraoch very interesting was using a table substraction.
It’s really all about table subtraction.
I was wondering if you could help me crack this one.
Here is the challenge:
Two tables 1Testdb y 2Testdb.
My first step was to select ID relationships ([2Testdb].Acc_id) on table 2Testdb for one given individual ([2Testdb].Bus_id). Then query table 1Testdb for records not mathcing my original selection from 2Testdb.
But other approaches are welcome.
Data and Structures:
USE [Challengedb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[1Testdb](
[Acc_id] [uniqueidentifier] NULL
[Name] [Varchar(10)] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[2Testdb](
[Acc_id] [uniqueidentifier] NULL,
[Bus_id] [uniqueidentifier] NULL
) ON [PRIMARY]
GO
Records on 1Testdb:
34455F60-9474-4521-804E-66DB39A579F3, John
C23523F6-2309-4F58-BB3F-EF7486C7AF8B, Pete
DC711615-3BE4-4B31-9EF2-B1314185CA62, Dave
E3AAB073-2398-476D-828B-92829F686A4C, Adam
Records on 2Testdb: (Relationship table, ex. Friend relationships)
Record #1: DC711615-3BE4-4B31-9EF2-B1314185CA62, 34455F60-9474-4521-804E-66DB39A579F3
Record #2: E3AAB073-2398-476D-828B-92829F686A4C, 34455F60-9474-4521-804E-66DB39A579F3
Record # 3: DC711615-3BE4-4B31-9EF2-B1314185CA62, E3AAB073-2398-476D-828B-92829F686A4C
Record # 4: E3AAB073-2398-476D-828B-92829F686A4C, DC711615-3BE4-4B31-9EF2-B1314185CA62
Challenge: Select from table 1Testdb only those records distinct that may not have a relationship with John [34455F60-9474-4521-804E-66DB39A579F3] on table 2Testdb.
Expected result should be (Who does John doesn’t have relationship with?):
C23523F6-2309-4F58-BB3F-EF7486C7AF8B, Pete
Thank you,
Valentin
Not sure exactly what you're asking; is it for all users in the first table that don't have a friendship with "John" based on the second table?
If so, use the "not exists" keyword to determine whether or not a record exists with the given query:
select a.*
from [1testdb] a
where not exists (
select * from [2testdb] b where a.acc_id = b.acc_id and b.subid = '34455F60-9474-4521-804E-66DB39A579F3'
)
and a.acc_id <> '34455F60-9474-4521-804E-66DB39A579F3'
I'm not sure how your columns are set up...looks like GUIDs, but this is the SQL Server syntax for getting it to work. I included a case where John could be in either the Acc_id or Bus_id column, so that's why there are 2 joins instead of one.
Declare #id NVarchar(50)
Set #id = '34455F60-9474-4521-804E-66DB39A579F3'
Select *
From 1Testdb
Left Outer Join 2Testdb As ForwardRelationship On ForwardRelationship.Acc_id = #id And ForwardRelationship.Bus_id = 1Testdb.Acc_id
Left Outer Join 2Testdb As ReverseRelationship On ReverseRelationship.Bus_id = #id And ReverseRelationship.Acc_id = 1Testdb.Acc_id
Where
ForwardRelationship.Acc_id Is Null And
ForwardRelationship.Bus_id Is Null And
ReverseRelationship.Acc_id Is Null And
ReverseRelationship.Bus_id Is Null And
1Testdb.Acc_id <> #id

Resources