how to use EF to select using DISTINCT and FOREIGN KEY together - c#

This may be very basic, but here we go, as I can´t solve that for now.
I´m using Entity Frameword for Oracle (Managed Driver) and would like to do get all following:
I have 2 database tables as follows:
TABLE_USER
ID INTEGER
NAME STRING
AGE INTEGER
Content:
0 JOHN 39
1 MARY 40
2 ALBERT 41
3 ROBERT 42
4 SARAH 43
5 PETER 44
TABLE_EVENTS
ID INTEGER
EVENT_NAME STRING
USER_ID INTEGER (FOREIGN KEY TO TABLE_USER.ID)
Content:
0 CREATE 1
1 CREATE 2
2 CREATE 5
3 DELETE 3
4 DELETE 0
5 CREATE 1
6 DELETE 3
7 CREATE 0
8 UPDATE 4
9 UPDATE 5
10 DELETE 1
I need to get all DISTINCT values from TABLE_EVENTS where the user age in TABLE_USER is of a certain condition (like AGE <= 40).
That example would give me the following list:
CREATE
DELETE
My code shall look like:
IQueryable<TABLE_USER> tableUser = dbContext.TABLE_USER;
IQueryable<TABLE_EVENTS> tableEvents = dbContext.TABLE_EVENTS;
///
/// Build the query
///
tableUserQuery = tableUser.Where(record => record => USER_ID == ??tableUser.ID?? &&
??tableUser.AGE < 30?? ).GroupJoin(???);
///
/// Execute que query
///
var dbList = query.ToList();
I was looking at GroupJoin and other stuff, but I can´t even figure out how to built this query, so all I´ve posted is a skeleton...
Appreciate any kind of help.

typically if 2 tables are linked by foreign key, EF generates the navigation property to reach the other entity and you can use this query.
List<string> events = dbContext.TABLE_EVENTS.Where(te=>te.TABLE_USER.AGE < 30).Select(te=>te.EVENT_NAME).Distinct().ToList();
If you don't see the foreign entity linked, then the query is
List<string> events = dbContext.TABLE_EVENTS.Join(dbContext.TABLE_USERS, te=>te.USER_ID, tu=>tu.ID, (te,tu)=> te).Where(te=>te.TABLE_USER.AGE < 30).Select(te=>te.EVENT_NAME).Distinct().ToList();
the above query basically does an inner join on the user id, applies the filter and gets the distinct values.

Related

Linq left join with multiple tables

Hi I am developing web application in .net. I have come across with below scenario.
Below is my first table.
perm_levelid scrn_id perm_id perm_read perm_write
40 1 2 1 1
41 2 2 1 1
42 3 2 1 1
Below is my second table.
scrn_id scrn_name
1 UserProfile
2 Change Password
3 Dashboard
4 Lease request
The relation between above two table is scrn_id
The output i am expecting is
scrn_id perm_id perm_read perm_write
1 2 1 1
2 2 1 1
3 2 1 1
4 0 0 0
I want total 4 rows in the result. scrn_id 1,2,3 matching in both tables so i should retrieve first table perm_read and perm_write values. Remaining value from 2 nd table also i want to get.
I tried as below.
List<screendetails> obj = new List<screendetails>();
obj = (from c in db.rolsp_perm_levelmapping
join mapdetails in db.rolsp_scrn_screen on c.scrn_id equals mapdetails.scrn_id
into mapObj
from wt in mapObj.DefaultIfEmpty()
where c.perm_id== permisssionID
select new screendetails {
scrn_id=c.scrn_id,
scrn_name= wt.scrn_name,
Read=c.perm_read,
Write=c.perm_write
}).ToList();
return obj;
Above query does not yields correct result. May i get some help here to fix this? Thank you
obj= (from scrn in db.rolsp_scrn_screen
from rmap in db.rolsp_perm_levelmapping
.Where(rl=>rl.scrn_id==scrn_id).DefaultIfEmpty() select new screendetails {
scrn_id=scrn.scrn_id,
scrn_name= scrn.scrn_name,
Read=rmap.perm_read,
Write=rmap.perm_write
}).ToList();
Try using this... Hope this helps...

Linq where on include

I'm stuck with this linq query.
I've this tables.
ID A B C D
1 some data
2 some other data
Then, For every record on that table I may have none or many rows
ID TableA_ID R
1 1 1
2 1 2
3 1 5
4 2 2
For example. Row 1 (some data) has 3 rows on table B.
I tried using
tableA.Include(x => x.tablebchilds.Where( d => d.R == 1)).ToList()
but it is not working. With many others varation.
The objective of this query is to return tableA.row #1 if I pass it 1 as value (value of R). Number <> 2 won't give any result.
Tables are linked on EF. So TableB.tableA_ID is Foreign key of tableA.ID
Edit #1
I tried the answers in the question marked as duplicated with no luck. Give that 2 tableA.rows if the user insert 1 as parameter, linq query should return Row #1, some data. If 2 is passed as parameter, nothing is return.
A working SQL statement is:
SELECT [TableA].* FROM [TableA] JOIN [TableB] ON [TableA].[Id] = [TableB].[TableA_Id] WHERE [TableB].[R] = 1
Thanks!
If you have database relationship properly configured this have to work.
tableA.Include(x => x.tableBChilds).Where(tableA => tableA.tableBChilds.Any(b => b.R== 1)).ToList();

SQL Show records that meet a provided criteria

I have the following table
CamId RegNumber DateSeen
5 G1234B 18/02/2014 11:54
3 G1234B 18/02/2014 11:51
5 G11854 18/02/2014 11:50
3 G11854 18/02/2014 11:49
3 G24581 18/02/2014 11:48
5 G24581 18/02/2014 11:47
I would like to retrieve all records with CamId 3 that do not have a later entry in CamId 5 based on the dateseen entry on CamId 3 for that particular reg number.
From the sampe data table above the system should return just one number plate G24581 as it has no later entries in CamId 5.
One method you can employ is to join onto the table twice so that in one table you have the values where CamID is 3 and the other is 5. Then you would want to get all records from the first table that do no have a record in the second table.
Select A.* from Table A
LEFT JOIN ( Select * from Table ) B on A.RegNumber = B.RegNumber AND A.CamID = 3 and B.CamID = 5 AND A.DateSeen <= B.DateSeen
WHERE B.CamID IS NULL
Try this:
var query = from r1 in db.Regs
where r1.CamId == 3 &&
!db.Regs.Any(r2 => r2.CamId==5 && r2.DateSeen>r1.DateSeen && r2.RegNumber==r1.RegNumber)
select r1;

select two columns from two different tables in the same db using mysql + use the output of query in C#

Dear Friends,
i want to select two columns from two different tables in the same db using mysql and set the output of the query to a variable in c#.
currently my code is as shown below:
MySqlCommand logcmdCheck = new MySqlCommand(query, connectionCheck);
string query = "SELECT DB.table1.column1,DB.table1.column2,DB.table2.column1,DB.table2.column2,DB.table2.column3 FROM DB.table1 WHERE DB.table1.column1=?x,DB.table2 WHERE DB.table2.column1=?y";
logcmdCheck.Parameters.AddWithValue("?x",UserName);
logcmdCheck.Parameters.AddWithValue("?y",emailID);
MySqlDataReader ldr = logcmdCheck.ExecuteReader();
A = ldr[0].ToString();
B = ldr[1].ToString();
C = ldr[2].ToString();
D = ldr[3].ToString();
E = ldr[4].ToString();
Error: Mysql query syntax is wrong.
Kindly please help me out with the mysql command to perform the requirement.
Thanks in advance
Suraj
You're going to have to use a SQL Join. Check it out here http://www.w3schools.com/sql/sql_join.asp. You need to have a foreign key in one of the tables that allows you to connect to the primary key of the other table. Every good database should be set up with tables that have foreign keys.
For example:
Table 1:
OrderNumber Name Order Total
1 John Smith 10.00
2 Sally Smith 5.00
3 Berry Jones 25.00
Table 2:
Item Number ItemTotal OrderNumber
1 5.00 1
2 5.00 1
3 2.50 2
4 2.50 2
5 25.00 3
In table 2 the OrderNumber is the foreign key that is able to join to table one. So your syntax would be:
SELECT * FROM table1 JOIN table2 ON table2.OrderNumber = table1.OrderNumber
That will give you one table which you can read from.

Issues With LINQ to SQL Query

I am having trouble getting one of my LINQ to SQL queries to work correctly. I have three tables setup as follows:
Vendors
id - primary key
Manufacturers
id - primary key
ManufacturerVendorRelationships
id - primary key
manufacturer_id - foreign key to manufacturer.id
vendor_id - foreign key to vendor.id
I am trying to write a LINQ to SQL query that will fetch the Vendors that are not currently related to a given manufacturer. For example, the following table data should only result in 2 vendors for the manufacturer with ID of 1. Can someone please help me with the LINQ to SQL for this example? Right now, the application is doing this logic. Thanks in advance.
Vendors
ID
1
2
3
4
5
Manufacturers
ID
1
2
3
4
5
ManufacturerVendorRelationships
ID ManufacturerID VendorID
1 1 1
2 1 2
3 1 3
Maybe something like this:
var result=(
from v in db.Vendors
where !db.ManufacturerVendorRelationships
.Select(s=>s.VendorID)
.Contains(v.ID)
select v
);
Or if you want it like a field:
var result=(
from v in db.Vendors
select new
{
v.ID,
HasManufacturer=db.ManufacturerVendorRelationships
.Select(s=>s.VendorID)
.Contains(v.ID)
}
);
where db is the linq data context
int id= 1;
var result =
dc.Vendors
.Where(v => !dc.ManufacturerVendorRelationships
.Any(rel => rel.VendorId == v.Id && rel.ManufacturerId == id));

Categories