var q = (from Labels in dc.tblArtworkDataLabels select Labels).ToList();
But I need this to do the quivalent of:
SELECT d.ID, d.labelID, d.dataID, d.data, l.templateID
FROM tblArtworkDataLabels AS d INNER JOIN
tblArtworkData AS l ON d.dataID = l.ID
WHERE (l.templateID = 238)
How do I do this in LINQ?
Edit
Sorry! Missed the WHERE clause on original statmenet!
var result = dc.tblArtworkDataLabels
.Join(dc.tblArtworkData, l => l.ID, d => d.dataID, (l, d) => new {l, d})
.Select(o => new {
Id = o.d.ID,
LabelId = o.d.labelID,
DataId = o.d.dataID,
Data = o.d.data,
TemplateId = o.l.templateID,
})
.Where(o => o.l.templateID == 238);
If you have a correct foreign key on tblArtworkData to the primary key on the tblArtworkDataLabels and have imported them correctly into the DBML designer you can have LINQ2SQL implicitly creating the join:
from l in tblArtworkData
where l.templateID = 238
select new {
Id = l.tblArtworkDataLabel.ID,
LabelId = l.tblArtworkDataLabel.labelID,
DataId = l.tblArtworkDataLabel.dataID,
Data = l.tblArtworkDataLabel.data,
TemplateId = l.templateID,
}
See my answer on the question "LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?" for how the implicit join translates to SQL.
Edit:
In the case I misunderstood your relations and you have many tblArtworkDataLabels to one tblArtworkData you have to turn the query the other way around
from d in tblArtworkDataLabels
where d.tblArtworkData.templateID = 238
select new {
Id = d.ID,
LabelId = d.labelID,
DataId = d.dataID,
Data = d.data,
TemplateId = d.tblArtworkData.templateID,
}
try
var q = (from Labels in dc.tblArtworkDataLabels
join data in dc.tblArtworkData on Labels.ID equals data.DataID select Labels).ToList();
Related
I have a situation where two tables should be joined with multiple columns with or condition. Here, I have a sample of sql query but i was not able to convert it into linq query.
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
This is how i have write linq query
await (from cm in Context.CustomerMaster
join li in list.PortalCustomerDetailViewModel
on new { OldNLKNo = cm.OldAcNo, NewNLKNo = cm.CustomerCode } equals new { OldNLKNo = li.OldNLKNo, NewNLKNo = li.NewNLKNo }
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
But this query doesn't returns as expected. How do I convert this sql query into linq.
Thank you
You didn't tell if list.PortalCustomerDetailViewModel is some information in the database, or in your local process. It seems that this is in your local process, your query will have to transfer it to the database (maybe that is why it is Tmp in your SQL?)
Requirement: give me all properties of a CustomerMaster for all CustomerMasters where exists at least one PortalCustomerDetailViewModel where
customerMaster.CustomerCode == portalCustomerDetailViewModel.NewNLKNo
|| customerMaster.OldAcNo == portalCustomerDetailViewModel.OldNLKNo
You can't use a normal Join, because a Join works with an AND, you want to work with OR
What you could do, is Select all CustomerMasters where there is any PortalCustomerDetailViewModel that fulfills the provided OR:
I only transfer those properties of list.PortalCustomerDetailViewModel to the database that I need to use in the OR expression:
var checkProperties = list.PortalCustomerDetailViewModel
.Select(portalCustomerDetail => new
{
NewNlkNo = portalCustomerDetail.NewNlkNo,
OldNLKNo = portalCustomerDetail.OldNLKNo,
});
var result = dbContext.CustomerMasters.Where(customerMaster =>
checkProperties.Where(checkProperty =>
customerMaster.CustomerCode == checkProperty.NewNLKNo
|| customerMaster.OldAcNo == checkProperty.OldNLKNo)).Any()))
.Select(customerMaster => new CustomerInfoViewModel
{
Id = customerMaster.Id,
Name = customerMaster.Name,
...
});
In words: from each portalCustomerDetail in list.PortalCustomerDetailViewModel, extract the properties NewNKLNo and OldNLKNo.
Then from the table of CustomerMasters, keep only those customerMasters that have at least one portalCustomerDetail with the properties as described in the OR statement.
From every remaining CustomerMasters, create one new CustomerInfoViewModel containing properties ...
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
You don't have to use the join syntax. Adding the predicates in a where clause could get the same result. Try to use the following code:
await (from cm in Context.CustomerMaster
from li in list.PortalCustomerDetailViewModel
where cm.CustomerCode == li.NewNLKNo || cm.OldAcNo = li.OldNLKNo
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
var result=_db.Customer
.groupjoin(_db.#temp ,jc=>jc.CustomerCode,c=> c.NewNLKNo,(jc,c)=>{jc,c=c.firstordefault()})
.groupjoin(_db.#temp ,jc2=>jc2.OldAcNo,c2=> c2.OldNLKNo,(jc2,c2)=>{jc2,c2=c2.firstordefault()})
.select(x=> new{
//as you want
}).distinct().tolist();
I am trying to convert this sql into linq but so far not able to
Below code is successfully giving result as I need
SELECT [dbo].[Ingredient].[IngredientId]
,[EnglishName]
,[HindiName]
,COUNT([dbo].[RecipeIngredient].RecipeId) As IngredientUsed
FROM [DB_A19C63_kmkb].[dbo].[Ingredient]
JOIN [dbo].[RecipeIngredient]
ON [dbo].[RecipeIngredient].IngredientId = [dbo].[Ingredient].[IngredientId]
WHERE [dbo].[RecipeIngredient].IngredientId = 39
GROUP BY [dbo].[Ingredient].[IngredientId]
,[EnglishName]
,[HindiName]
Result
IngredientId EnglishName HindiName IngredientUsed
39 Asafoetida Hing 628
My Linq Code
(from x in _unitOfWork.IngredientRepository.GetManyQueryable()
select new IngredientEntity
{
IngredientId = x.IngredientId,
EnglishName = x.EnglishName,
HindiName = x.HindiName,
Pros = x.Pros,
Cons = x.Cons,
Calories = x.Calories,
IngredientUsed = (from z in _unitOfWork.RecipeIngredientRepository.GetAll()
where z.IngredientId == x.IngredientId
select z.RecipeId).Count(),
DepartmentId = x.DepartmentId
}).OrderBy(x => x.EnglishName);
Thanks in Advance
I know there are probably a ton of questions like this already but i'm having trouble
select *
from [Group]
where GroupId not in
(select GroupId
from CustomerGroup
where CustomerId = 189621)
i have myGroups = db.Groups.Where(e=> e.GroupId), but how do i say not in?
i am kind of there
var myGroups = from a in db.Groups
where!(from b in db.CustomerGroups
where b.CustomerId == customer.CustomerId )
var groupIds = from cg in db.CustomerGroups
where cg.CustomerId == 189621
select cg.GroupId;
var myGroups = from g in db.Groups
where !groupIds.Contains(g.GroupId)
select g;
Need a list to disqualify first. NOT IN is basically a !(IEnumerable).Contains() in LINQ (since you're comparing to a set).
Using lambda expression, you probably can do it like this
var groupIds = db.CustomerGroups.Where(x => x.CustomerId == 189621).Select(x => x.GroupId);
var myGroups = db.CustomerGroups.Where(x => !groupIds.Contains(x.GroupId)).ToList();
How do i change the training events into a left outer join in training events im very basic at linq so excuse my ignorance its not retrieve records that don't have any trainnevent reference attached to it
var q = from need in pamsEntities.EmployeeLearningNeeds
join Employee e in pamsEntities.Employees on need.EmployeeId equals e.emp_no
join tevent in pamsEntities.TrainingEvents on need.TrainingEventId equals tevent.RecordId
where need.EmployeeId == employeeId
where need.TargetDate >= startdate
where need.TargetDate <= enddate
orderby need.TargetDat
It's best to use where in combination with DefaultIfEmpty.
See here: LEFT JOIN in LINQ to entities?
var query2 = (
from users in Repo.T_Benutzer
from mappings in Repo.T_Benutzer_Benutzergruppen.Where(mapping => mapping.BEBG_BE == users.BE_ID).DefaultIfEmpty()
from groups in Repo.T_Benutzergruppen.Where(gruppe => gruppe.ID == mappings.BEBG_BG).DefaultIfEmpty()
//where users.BE_Name.Contains(keyword)
// //|| mappings.BEBG_BE.Equals(666)
//|| mappings.BEBG_BE == 666
//|| groups.Name.Contains(keyword)
select new
{
UserId = users.BE_ID
,UserName = users.BE_User
,UserGroupId = mappings.BEBG_BG
,GroupName = groups.Name
}
);
var xy = (query2).ToList();
Which is equivalent to this select statement:
SELECT
T_Benutzer.BE_User
,T_Benutzer_Benutzergruppen.BEBG_BE
-- etc.
FROM T_Benutzer
LEFT JOIN T_Benutzer_Benutzergruppen
ON T_Benutzer_Benutzergruppen.BEBG_BE = T_Benutzer.BE_ID
LEFT JOIN T_Benutzergruppen
ON T_Benutzergruppen.ID = T_Benutzer_Benutzergruppen.BEBG_BG
select colId,
colTaskType,
MaxID
from tblTaskType
join (
select tblCheckList.colTaskTypeID,
max(colItemNumber) MaxID
from tblCheckList
group by colTaskTypeID
) x on coltaskTypeID = tblTaskType.colID
Assuming you are using linq-to-sql and have the two tables in a datacontext.
The more or less exact translation would be:
var maxChecks = from checks in DataContext.tblChecklist
group checks by checks.colTaskTypeID into g
select new { colTaskTypeID, max = g.Group.Max(x => x.colItemNumber) };
var result = from t in DataContext.tblTaskType
join c in maxChecks on t.colTaskTypeID equals c.colTaskTypeID
select new { t.colId, t.colTaskTypeID, c.max };
But you could try:
var result = from t in DataContext.tblTaskType
select new {
t.colId,
t.colTaskTypeID,
Max = (from c in DataContext.tblChecklist
where c.colTaskTypeID == t.colTaskTypeID
select c.colItemNumber).Max() };