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();
Related
I have two DataTables and I want to select the rows from the first one which are not present in second one, both tables have 3 Keys custnum, shiptonum, connum
For example:
Table Contacts
custnum shiptonum connum column
1 1 1 data1
2 2 2 data2
3 3 3 data3
4 4 4 data4
Table Invitations
custnum shiptonum connum column
1 1 1 data11
3 3 3 data33
I'd like the result to be:
Table Result
custnum shiptonum connum column
2 2 2 data2
4 4 4 data4
I already tried using
var differences = table1.AsEnumerable().Except(table2.AsEnumerable(),DataRowComparer.Default);
but it didn't work. For example in my testing in Contacts table I have 14,389 records, in Invitations table I have two records that exist in Contacts table the count after using the abovesolution was 14,389 instead of 14,387 (removing the two records from Invitations table).
You wrote:
I want to select the rows from the first one which are not present in second one
From your example, I see that you don't want to select rows from the first table that are not rows in the second table, but that you only want to take the values of the keys into account:
I want to select all rows from tableA which have keys with values that are not keys from tableB
You didn't define your tables. They might be IQueryable, or IEnumerable, for your LINQ statements there is not a big difference. Try to avoid AsEnumerable, especially if your data source is in a different process, like a database management system. The other process is much more efficient in executing your query than your process. AsEnumerable transports all data from your other process to your process, which is a relatively slow process. Therefore as a rule: Only use AsEnumerable this if you really need to,
The second definition defines clearer what you want: apparently from tableB you only need the keys:
var keysTableB = tableB.Select(row => new
{
CustNum = row.custNum,
ShipToNum = row.shiptonum,
ConNum = row.connum,
});
In words: from every row in tableB make one new object of anonymous type with three properties: CustNum, ShipToNum and ConNum
Select uses lazy execution. No query is executed, only property Expression is changed.
Now you want to keep only the rows from tableA that have a key that is a member of sequence keysTableB: if you want to keep a subset of a sequence, use Where
var result = tableA.Where(row => keysTableB.Contains(new
{
CustNum = row.custNum,
ShipToNum = row.shiptonum,
Connum = row.connum,
}));
In words: from every row in tableB keep only those rows that have a key that is also in keysTableB, using value equality.
TODO: consider concatenating these two LINQ statements into one.I doubt whether this would improve performance. It surely will deteriorate readability of your code, and thus decreases changeability / maintenance / testability.
for (int i=0;i<table1.rows.count;i++)
{
var rowExists = from dr in table2.AsEnumerable()
where dr.Field<typeofcolumn>("colum_name")==table1.Rows[i]["column_name"]
select dr;
if(rowExists.ToList().Count==0)
{
//here u import row table1.rows[i] to new table
}
}
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...
Im newbie to linq and im using linq query to retrieve data from the table.My idea is to list all the cashsafes corresponding to a particular user and show it in dropdownlist.
The table structure is shown below
Table 1
cashsafeid cashsafename
1 cashsafe1
2 cashsafe2
3 cashsafe3
Table 2
Id UserId Cashsafeid
1 100 1,2,3
2 101 1,3
I've to get the cashsafename of a particular user say 100.How can i achieve it
The below code is the one i've tried but am stuck
List<Cashsafe> cashsafes=(from c in db.Table 1
where c.CashsafeId contains() )--Cannot go further
You store User's Cachsafeid column in very inefficient way - it doesn't allow to generate efficient SQL for LINQ provider. So the following solution has bad performance - if you care about that - change your table structure.
var user = db.Table2.Single(u => u.UserId == 100);
var cachfeIds = user.Cashsafeid.Split(',').Select(int.Parse).ToArray();
var cachefes = db.Table1.Where(c => cachfeIds.Contains(c.Id)).ToList();
Basically you need to join to tables, but foreign key is "virtual" - it is only in your mind. To retrieve foreign key values we must split the Cachsafeid column's value of every user to retrieve linked cachefes. And only then retrieve the cachefes with separate request (I think LINQ will retrieve all values from table and the execute Where part in C# code).
if you have no idea of join you can use
int x = 0;
List<int> Users = db.table2.FirstOrDefault(m => m.UserId == 100).Cashsafeid.Split(',').ToList().Where(str => int.TryParse(str, out x)).Select(str => x).ToList(); ;
var content = db.table1.Where(m => Users.Contains(m.cashsafeid)).ToList();
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.
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));