I have a SQL statement, that I want to implement in a .NET website project. I don't understand how to join in a particular field, as the fields aren't available when I just select from the table.
My SQL
SELECT *
FROM [vResidence] c
JOIN [vJobs] j on c.UID = j.UID
This is the LINQ I have tried, but I am stuck at the 'ON' part:
results = (from j in vJobs
join cr in vResidence on ??? )
When I try 'j.', the only option I get is 'equals'.
You can follow as this.connect to tables as JOIN use equals keyword
var result = from r in vResidence
join j vJobs on r.UID equals j.UID
select new {[yourcolnum]};
You can try this
var result = (from j in vJobs
join cr in vResidence
on j.UID equals cr.UID
select new {
...
}).ToList();
The Linq expression is the following:
from t1 in Table1
join t2 in Table2
on t1.ID equals t2.ID
The join clause on must be do in order: first the first table, then the second.
The keyword equals must be use.
Apart from the above Linq answers, we can do JOIN using Enumerable.Join extension with Lambda expressions. Try something like,
var result = vJobs.Join(vResidence, jb => new { jb.UID }, res => new { res.UID },
(jb, res) => new { jb, res })
.Select(x => x.jb) //Select the required properties (from both objects) with anonymous object or select left/right object
.ToList();
C# Fiddle with sample data.
I wrote this SQL query
select
acc.DepartmentID,
dept.DepartmentName,
dept.DepartmentDivision,
county.CountyName,
sp.StateProvinceID
from [AccountDepartmentXREF] acc
inner join [Department] dept on dept.DepartmentID = acc.DepartmentID
left join [DepartmentStateCountyXREF] dscx on dscx.DepartmentID = acc.DepartmentID
left join [StateCounty] county on county.StateCountyID = dscx.StateCountyID
inner join [StateProvince] sp on sp.StateProvinceID = dept.StateProvinceID
where acc.AccountID = 1
and want to rewrite it using LINQ, but I always get confused when writing left joins in LINQ, so I decided to use a convertor and went with Linqer and this is what it produced
from acc in db.AccountDepartmentXREF
join dscx in db.DepartmentStateCountyXREF on acc.DepartmentID equals dscx.DepartmentID into dscx_join
from dscx in dscx_join.DefaultIfEmpty()
join county in db.StateCounty on new { StateCountyID = Convert.ToInt32(dscx.StateCountyID) } equals new { StateCountyID = county.StateCountyID } into county_join
from county in county_join.DefaultIfEmpty()
join sp in db.StateProvince on acc.Department.StateProvinceID equals sp.StateProvinceID
where
acc.AccountID == 1
select new {
acc.DepartmentID,
acc.Department.DepartmentName,
acc.Department.DepartmentDivision,
CountyName = county.CountyName,
sp.StateProvinceID
}
so when I put everything together in code
public List<DepartmentList> GetDepartmentsByAccountID(string email)
{
HWC = new HWCEntities();
List<DepartmentList> result = new List<DepartmentList>();
int id = CurrentUserID(email);
List<AccountDepartmentXREF> adx = HWC.AccountDepartmentXREFs.Where(w => w.AccountID == id).ToList();
foreach(var a in adx)
{
var query = from acc in HWC.AccountDepartmentXREFs
join dscx in HWC.DepartmentStateCountyXREFs on acc.DepartmentID equals dscx.DepartmentID into dscx_join
from dscx in dscx_join.DefaultIfEmpty()
join county in HWC.StateCounties on new { StateCountyID = Convert.ToInt32(dscx.StateCountyID) } equals new { StateCountyID = county.StateCountyID } into county_join
from county in county_join.DefaultIfEmpty()
join sp in HWC.StateProvinces on acc.Department.StateProvinceID equals sp.StateProvinceID
where
acc.AccountID == a.AccountID
select new
{
acc.DepartmentID,
acc.Department.DepartmentName,
acc.Department.DepartmentDivision,
CountyName = county.CountyName,
sp.StateProvinceID
};
foreach(var b in query)
{
result.Add(new DepartmentList
{
DepartmentID = b.DepartmentID,
DepartmentName = b.DepartmentName,
StateProvinceID = b.StateProvinceID,
DivisionName = b.DepartmentDivision,
CountyName = b.CountyName
});
}
}
return result;
}
I get the error
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' method, and this method cannot be translated into a store expression.
at the
foreach(var b in query)
Any idea's on how to fix this? I have looked around but other solutions I found aren't dealing with joins
Linq doesn't support the Convert.ToInt32(dscx.StateCountyID) method inside the query because this will need to be converted to sql for execution on the db.
I am not sure what datatype StateCountyID is in both tables but you will need to use some sql compatible conversion method like SqlFunctions.StringConvert() to get them to the same datatype.
Convert them to Strings
from acc in HWC.AccountDepartmentXREFs
join dscx in HWC.DepartmentStateCountyXREFs on acc.DepartmentID equals dscx.DepartmentID into dscx_join
from dscx in dscx_join.DefaultIfEmpty()
join county in HWC.StateCounties on new { StateCountyID = dscx.StateCountyID.ToString() } equals new { StateCountyID = county.StateCountyID.ToString() }
or use the below:
dscx.StateCountyID equals SqlFunctions.Convert(county.StateCountyID)
I figured out why I was getting that error. It was because I had StateCountyID as nullable in my DepartmentStateCountyXREF table. Once I changed the StateCountyID column from a nullable and then removed the Convert.ToInt32, everything worked.
I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an ON clause in C#.
How do you represent the following in LINQ to SQL:
select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
It goes something like:
from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}
It would be nice to have sensible names and fields for your tables for a better example. :)
Update
I think for your query this might be more appropriate:
var dealercontacts = from contact in DealerContact
join dealer in Dealer on contact.DealerId equals dealer.ID
select contact;
Since you are looking for the contacts, not the dealers.
And because I prefer the expression chain syntax, here is how you do it with that:
var dealerContracts = DealerContact.Join(Dealer,
contact => contact.DealerId,
dealer => dealer.DealerId,
(contact, dealer) => contact);
To extend the expression chain syntax answer by Clever Human:
If you wanted to do things (like filter or select) on fields from both tables being joined together -- instead on just one of those two tables -- you could create a new object in the lambda expression of the final parameter to the Join method incorporating both of those tables, for example:
var dealerInfo = DealerContact.Join(Dealer,
dc => dc.DealerId,
d => d.DealerId,
(dc, d) => new { DealerContact = dc, Dealer = d })
.Where(dc_d => dc_d.Dealer.FirstName == "Glenn"
&& dc_d.DealerContact.City == "Chicago")
.Select(dc_d => new {
dc_d.Dealer.DealerID,
dc_d.Dealer.FirstName,
dc_d.Dealer.LastName,
dc_d.DealerContact.City,
dc_d.DealerContact.State });
The interesting part is the lambda expression in line 4 of that example:
(dc, d) => new { DealerContact = dc, Dealer = d }
...where we construct a new anonymous-type object which has as properties the DealerContact and Dealer records, along with all of their fields.
We can then use fields from those records as we filter and select the results, as demonstrated by the remainder of the example, which uses dc_d as a name for the anonymous object we built which has both the DealerContact and Dealer records as its properties.
var results = from c in db.Companies
join cn in db.Countries on c.CountryID equals cn.ID
join ct in db.Cities on c.CityID equals ct.ID
join sect in db.Sectors on c.SectorID equals sect.ID
where (c.CountryID == cn.ID) && (c.CityID == ct.ID) && (c.SectorID == company.SectorID) && (company.SectorID == sect.ID)
select new { country = cn.Name, city = ct.Name, c.ID, c.Name, c.Address1, c.Address2, c.Address3, c.CountryID, c.CityID, c.Region, c.PostCode, c.Telephone, c.Website, c.SectorID, Status = (ContactStatus)c.StatusID, sector = sect.Name };
return results.ToList();
You create a foreign key, and LINQ-to-SQL creates navigation properties for you. Each Dealer will then have a collection of DealerContacts which you can select, filter, and manipulate.
from contact in dealer.DealerContacts select contact
or
context.Dealers.Select(d => d.DealerContacts)
If you're not using navigation properties, you're missing out one of the main benefits on LINQ-to-SQL - the part that maps the object graph.
Use Linq Join operator:
var q = from d in Dealer
join dc in DealerConact on d.DealerID equals dc.DealerID
select dc;
basically LINQ join operator provides no benefit for SQL. I.e. the following query
var r = from dealer in db.Dealers
from contact in db.DealerContact
where dealer.DealerID == contact.DealerID
select dealerContact;
will result in INNER JOIN in SQL
join is useful for IEnumerable<> because it is more efficient:
from contact in db.DealerContact
clause would be re-executed for every dealer
But for IQueryable<> it is not the case. Also join is less flexible.
Actually, often it is better not to join, in linq that is. When there are navigation properties a very succinct way to write your linq statement is:
from dealer in db.Dealers
from contact in dealer.DealerContacts
select new { whatever you need from dealer or contact }
It translates to a where clause:
SELECT <columns>
FROM Dealer, DealerContact
WHERE Dealer.DealerID = DealerContact.DealerID
Inner join two tables in linq C#
var result = from q1 in table1
join q2 in table2
on q1.Customer_Id equals q2.Customer_Id
select new { q1.Name, q1.Mobile, q2.Purchase, q2.Dates }
Use LINQ joins to perform Inner Join.
var employeeInfo = from emp in db.Employees
join dept in db.Departments
on emp.Eid equals dept.Eid
select new
{
emp.Ename,
dept.Dname,
emp.Elocation
};
Try this :
var data =(from t1 in dataContext.Table1 join
t2 in dataContext.Table2 on
t1.field equals t2.field
orderby t1.Id select t1).ToList();
OperationDataContext odDataContext = new OperationDataContext();
var studentInfo = from student in odDataContext.STUDENTs
join course in odDataContext.COURSEs
on student.course_id equals course.course_id
select new { student.student_name, student.student_city, course.course_name, course.course_desc };
Where student and course tables have primary key and foreign key relationship
try instead this,
var dealer = from d in Dealer
join dc in DealerContact on d.DealerID equals dc.DealerID
select d;
var Data= (from dealer in Dealer join dealercontact in DealerContact on dealer.ID equals dealercontact.DealerID
select new{
dealer.Id,
dealercontact.ContactName
}).ToList();
var data=(from t in db.your tableName(t1)
join s in db.yourothertablename(t2) on t1.fieldname equals t2.feldname
(where condtion)).tolist();
var list = (from u in db.Users join c in db.Customers on u.CustomerId equals c.CustomerId where u.Username == username
select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();
Write table names you want, and initialize the select to get the result of fields.
from d1 in DealerContrac join d2 in DealerContrac on d1.dealearid equals d2.dealerid select new {dealercontract.*}
One Best example
Table Names : TBL_Emp and TBL_Dep
var result = from emp in TBL_Emp join dep in TBL_Dep on emp.id=dep.id
select new
{
emp.Name;
emp.Address
dep.Department_Name
}
foreach(char item in result)
{ // to do}
How to convert an SQL to LINQ? Basically, I have a project_mstr table that has a PR_CLASS, PR_TYP and PR_GRP columns. Those 3 columns are values in the params_mstr under param_cd. For example, there's a record that has a PR_TYP value in param_cd with a Regular as its corresponding param_val value.
I installed Linquer but I'm not comfortable using it since I still have to create a connection to my database. I can't also find an online SQL to LINQ converter. So I'm asking the good guys here to please help me with the conversion.
SELECT
c.pr_id, c.pr_class, c.pr_typ, c.pr_grp, cp.pr_price,
c.gl_acct_id, c.pr_DESC "Project",
pm.param_val "Project Class", pm2.param_val "Project Type", pm3.param_val "Project Group"
FROM project_mstr c
JOIN
params_mstr pm ON c.pr_class = pm.param_id AND pm.param_cd = 'PR_CLASS'
JOIN
params_mstr pm2 ON c.pr_typ = pm2.param_id AND pm2.param_cd = 'PR_TYP'
JOIN
params_mstr pm3 ON c.pr_grp = pm3.param_id AND pm3.param_cd = 'PR_GRP'
JOIN
pr_price_mstr cp ON c.pr_id = cp.pr_id
JOIN
gl_acct_mstr gl ON c.gl_acct_id = gl.gl_acct_id
ORDER BY
c.crea_dt DESC;
LINQ-to-SQL only support equijoins, so if you need to introduce multiple values into the join, you can create an anonymous class to represent all of the values being joined on (note that the anonymous classes need to be the same type, which means that they need to have (1) exactly the same names of fields (2) of exactly the same type (3) in exactly the same order).
from c in ProjectMstr
join pm in ParamsMstr on new { ParamId = c.ChClass, ParamCd = "CH_CLASS" } equals new { pm.ParamId, pm.ParamCd }
join pm2 in ParamsMstr on new { ParamId = c.ChClass, ParamCd = "CH_TYP" } equals new { pm2.ParamId, pm2.ParamCd }
join pm3 in ParamsMstr on new { ParamId = c.ChClass, ParamCd = "CH_GRP" } equals new { pm3.ParamId, pm3.ParamCd }
// …
orderby c.CreaDt descending
select new {
c.ChId,
// …
ProjectClass = pm.ParamVal,
ProjectType = pm2.ParamVal,
ProjectGroup = pm3.ParamVal,
}
Alternatively, if it doesn't change the logic of the query, you can pull out the constant value from the join into a where.
from c in ProjectMstr
join pm in ParamsMstr on c.ChClass equals pm.ParamId
join pm2 in ParamsMstr on c.ChClass equals pm2.ParamId
join pm3 in ParamsMstr on c.ChClass equals pm3.ParamId
// …
where pm.ParamCd == "CH_CLASS"
where pm2.ParamCd == "CH_TYP"
where pm3.ParamCd == "CH_GRP"
orderby c.CreaDt descending
select new {
c.ChId,
// …
ProjectClass = pm.ParamVal,
ProjectType = pm2.ParamVal,
ProjectGroup = pm3.ParamVal,
}
I am working on a WinForms project which requires to use Linq-To-Sql. I have been able to create my DataContext using the SqlMetal tool, and make some queries. But right now I have a problem that I havent been able to solve.
I am trying to make a LEFT OUTER JOIN as following:
MyDatabase db = new MyDatabase(...);
var query = from p in db.ParentTable
join t in db.ChildTable on new {A = p.child_ID, B = p.OtherID}
equals new {A = t.ID, B = t.OtherID} into j1
from c in j1.DefaultIfEmpty()
select new
{
...
};
When I write this query an error is raised at compile-time in the join word:
The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'
I know this error is caused by the comparison between p.child_ID and t.ID since p.child_ID is int? and t.ID is int. But, How can I solve this? How can I perform the LEFT OUTER JOIN without having this error??
p.child_ID is int? since this column is marked as IS NULL in SQL.
Hope someone can help me, thanks in advance.
You can use GetValueOrDefault() method. It retrieves the value of the current Nullable object, or the object's default value.
In terms of your example :
var query = from p in db.ParentTable
join t in db.ChildTable on new {A = p.child_ID.GetValueOrDefault(0), B = p.OtherID}
equals new {A = t.ID, B = t.OtherID} into j1
from c in j1.DefaultIfEmpty()
select new
{
...
};
If the p.child_ID become null than it will return 0. Hope this will help !!
The first problem was that the property names should be the same as said casperOne♦, but the second problem is that you're comparing a nullable-int, p.child_ID, with a non-nullable-int, t.ID. So you could use the null-coalescing operator in this way:
(int)(p.child_ID ?? default(int))
In this case returns p.child_ID if it isn't null else returns default(int), that is 0.
The query will be:
var query = from p in db.ParentTable
join t in db.ChildTable on new {A = (int)(p.child_ID ?? default(T)), B = p.OtherID}
equals new {A = t.ID, B = t.OtherID} into j1
from c in j1.DefaultIfEmpty()
select new
{
//...
};