Linq to join 2 tables and use contains for both tables - linq

Ex:join master table with emp table and fetch empname from master table based on Id present in emp table and search if it contains specific string passed as parameter in master or search I'd passed in emp table.. It basically autocomplete search where u can search based on Id and also name
I want equivalent linq for below sql qwery
select app.employeeid, emp.employeename
from applicant app
join [EmployeeMaster] emp on app.employeeid = emp.EmployeeId
where app.employeeid like '%empid%' or emp.EmployeeName like '%empname%'
Can someone please help.

Welcome to the community Deepa,
You can use this query.
Please note that you cannot use like in the linq-to-sql, and you have to use Contains instead. Read this post for more information.
applicant
.Join(EmployeeMaster, app => app.employeeid, emp => emp.EmployeeId, (app, emp) => new { app, emp })
.Where(x => x.app.employeeid.Contains("1") || x.emp.Employeename.Contains("our"))
.Select(x => new
{
x.app.employeeid,
x.emp.Employeename,
});
By the way, if Applicant.employeeid is the same as EmployeeMaster.EmployeeId, then you don't need to join these two tables; unless your select or criteria clauses are different.

Try this:
var q = (from app in applicantList join emp in EmployeeMasterList on app.employeeid equals emp.EmployeeId where app.employeeid.Contains(empid) || emp.EmployeeName.Contains(empname) select new{ app.employeeid, emp.employeename }).ToList();

Related

Get data from both tables in LINQ

I am trying to fetch an IP-address column which is present in both tables, A and B. Table A has many IP-adresses and a specific IP-address which is not present in table B. I want distinct IP-addresses from both the tables. That means I want all IP-adresses from table A which are not present in table B, plus all IP-adresses from table B which are not present in table A. I am trying the below code which is only giving me the IP-adresses which are not present in table B. Please help.
var ips= (from a in CS.A
where !CS.B.Any(f => f.IPAddress == a.IPAddress)
select a.IPAddress).Distinct();
You can simply use this
var ips= ((from a in CS.A
where !CS.B.Any(f => f.IPAddress == a.IPAddress)
select a.IPAddress).Distinct()).Union((from b in CS.B
where !CS.A.Any(f => f.IPAddress == b.IPAddress)
select b.IPAddress).Distinct());
You can just Concat both IP columns and group by the IPs.
Then only select the groups which have a count of 1 (= IP only occurs in one table)
var res =
(from ip in CS.A.Select(x => x.ip)
.Distinct()
.Concat(CS.B.Select(x => x.ip).Distinct())
group ip by ip into grp
where grp.Count() == 1
select grp.Key).ToList();
You can test this with the following example:
var x1 = Enumerable.Range(0, 20);
var x2 = Enumerable.Range(5, 20);
var res =
(from ip in x1.Select(x => x).Distinct().Concat(x2.Select(x => x).Distinct())
group ip by ip into grp
where grp.Count() == 1
select grp.Key).ToList();
res.ForEach(Console.WriteLine);
My first suggestion would be to use a store procedure to achieve that. Something along the lines of:
SELECT tblA.ip, tblB.ip FROM Table1 tblA
INNER JOIN Table2 tblB
ON 1=1
GROUP BY tblA.ip
the "ON" here will give you a condition that is always true.
Roughly the same query should work with linq as well. Experiment :-)
edit
UNION is also an option, however most not as easily read by non-SQL developers.
Select distinct cmnTbl.ip from (SELECT tblA.ip from Table1 tblA UNION SELECT tblB.ip from Table1) cmnTbl

How to return values from query when joining multiple tables in Linq?

I have a Linq queries that have tables join and couple of tables inner join together. Sometimes I got an error from the query when table is empty. What I trying to do is I am tryting to get a value from table even if other table is empty.
Thanks in Advance.
You need to do left join
Assuming left join between customer and order table.
var query =
from customer in dc.Customers
from order
in dc.Orders
.Where(o => customer.CustomerId == o.CustomerId)
.DefaultIfEmpty()
select new { Customer = customer, Order = order }
Also refer below link
http://forums.asp.net/t/1792428.aspx/1

SQL to LINQ query asp.net

I am currently trying to get some statistics for my website but i cant seem to create the query for my database to get the username that if found most frequent in all the rows.
The sql query should look something like this:
SELECT username FROM Views GROUP BY 'username' ORDER BY COUNT(*) DESC LIMIT 1
How do i make that query in my controller?
var username = db.Views.GroupBy(v => v.username).OrderByDescending(g => g.Count()).First().Key
(from a in Views
group a by a.username into b
let c = b.count()
orderby c descending
select a.username).take(1);
Your query conversion .....
This is how you do that query using LINQ:
var temp = (from a in Views
group a.username by a.username into b
orderby b.Count() descending
select b.Key).Take(1);
You can't do LIMIT 1 (mysql), since LinqToSql only generates TSql from MSSqlServer.

How do I return a table in LINQ that relies on a join/subquery?

I need the fields in 1 table contingent on 1 property matching rows in another table.
I can write this query in SQL with a subquery as such:
SELECT *
FROM Table1
WHERE Property1 IN
(
SELECT Property1
FROM Table2
WHERE Property0 = 1
)
But I read here that it's less complicated and just as easy to write with a join, which I did. However, so far I'm unable to return just Table1 as I'd like since I'm using a join, which if I'm not mistaken, requires me to create this anonymous type, as below. What I did here works (I created another object with the same properties of Table1 I need), but I can't help thinking there's a better way to do this.
Table1.Join(Table2, t1 => t1.Property1, t2 => t2.Property1, (t1, t2) => new
{
t1.Property1,
t1.Property2,
t1.Property3
})
.Select(ob => new UnnecessaryObject
{
Property1 = ob.Property1,
Property2 = ob.Property2,
Property3 = ob.Property3
}
I also tried just creating a Table1 in the .Select part, but I got an error about explicit construction not being allowed.
Just to clarify, I'd like to be able to return the IQueryable of type Table1, which it seems like I ought to be able to do without having to create UnnecessaryObject...but I'm still pretty new to LINQ, so I'd appreciate any help you can offer. Thanks in advance.
You could just do:
from t1 in table1
join t2 in table2 on t1.property1 equals t2.property1
select t1;
That would return a collection of table1 objects. This assumes from your example table1 is a collection of table1 objects and table2 is a collection of table2 objects.
The best translation of your original query I can come up with is:
from item in context.Table1
where context.Table2
.Where(x => x.Property0 == 0)
.Any(x => x.Property1 == item.Property1)
select item
This selects all items from Table1, where there's an item with matching Property1 and Property0 == 0 from Table2
It can also be solved with a join indeed. To get an efficient join, you need to have a relation between the two tables. Then you can do something like assuming the relation is called RelatedItems:
from item in context.Table1
join relatedItem in item.RelatedItems
on item.Property1 equals relatedItem.Property
where relatedItem.Property0 == 0
select item
This is equivalent to the SQL:
SELECT *
FROM Table1
JOIN Table2 ON Table1.Property1 = Table2.Property1
WHERE Table2.Property0 = 0

Linq To Entity Framework selecting whole tables

I have the following Linq statement:
(from order in Orders.AsEnumerable()
join component in Components.AsEnumerable()
on order.ORDER_ID equals component.ORDER_ID
join detail in Detailss.AsEnumerable()
on component.RESULT_ID equals detail.RESULT_ID
where orderRestrict.ORDER_MNEMONIC == "MyOrderText"
select new
{
Mnemonic = detail.TEST_MNEMONIC,
OrderID = component.ORDER_ID,
SeqNumber = component.SEQ_NUM
}).ToList()
I expect this to put out the following query:
select *
from Orders ord (NoLock)
join Component comp (NoLock)
on ord .ORDER_ID = comp.ORDER_ID
join Details detail (NoLock)
on comp.RESULT_TEST_NUM = detail .RESULT_TEST_NUM
where res.ORDER_MNEMONIC = 'MyOrderText'
but instead I get 3 seperate queries that select all rows from the tables. I am guessing that Linq is then filtering the values because I do get the correct values in the end.
The problem is that it takes WAY WAY too long because it is pulling down all the rows from all three tables.
Any ideas how I can fix that?
Remove the .AsEnumerable()s from the query as these are preventing the entire query being evaluated on the server.

Resources