Here is my sql query as follow
select enq_Id,enq_FromName,
enq_EmailId,
enq_Phone,
enq_Subject,
enq_Message,
enq_EnquiryBy,
enq_Mode,
enq_Date,
ProductId,
(select top 1 image_name
from tblProductImage as i
where i.product_id=p.product_Id) as imageName,
p.product_Name,
p.product_code
from tblEnquiry as e
inner join tblProduct as p ON e.ProductId=p.product_Id
where ProductId is not null
And I try to convert this sql statement into linq as follow
var result = from e in db.tblEnquiries
join d in db.tblProducts
on e.ProductId equals d.product_Id
where e.ProductId != null
orderby e.enq_Date descending
select new {
e.enq_Id,
e.enq_FromName,
e.enq_EmailId,
e.enq_Phone,
e.enq_Subject,
e.enq_Message,
e.enq_EnquiryBy,
e.enq_Mode,
e.enq_Date,
d.product_Id,
d.product_Name,
imageName = (from soh in db.tblProductImages
where soh.product_id == e.ProductId
select new { soh.image_name }).Take(1)
};
But problem its giving me imageName in a nested list but i want that imageName just as a string .
I also check by using quick watch and in following image you can see that imageName appearing in inner list .
Instead of Take(1) which returns sequence IEnumerable<string>, use FirstOrDefault() which returns single string value (or null if there is no results). Also don't create anonymous type for subquery result:
imageName = (from soh in db.tblProductImages
where soh.product_id == e.ProductId
select soh.image_name).FirstOrDefault()
BTW FirstOrDefault() generates TOP(1) SQL.
Related
I have a linq query with a where clause as below
var ExistingGroupDataSource = (from ppatg in dbContext.XXXXXXXXX
join pd1 in dbContext.XXXXXXXXXXX on ppatg.ScheduleID equals pd1.ScheduleID
where pd1.GroupID == null
select
new
{
FinishPDI = pd1.ProductionDateID,
FinishingDate = pd1.WorkFlowDate,
ppatg.GroupName,
ppatg.PNTGroupID
});
In the database GroupID is an int that can be null. The linq query returns rows without the filtered where clause but none when I include the where clause. There are null values in the GroupId column in the database.
It is definitely this statement that produces no results. All the literature on the subject online says that this is equivalent to
pd1.GroupID is null // in sql
I am getting results that contradict this
Sql code is
select pd1.ProductionDateID as FinishPDI, pd1.WorkflowDate as FinishingDate,GroupName ,PNTGroupId
from XXXXXXXXXXXX
inner join XXXXXXXXXXXX pd1 on
XXXXXXXXXXXX.ScheduleId = pd1.ScheduleID
where pd1.GroupID is null
You can combine your where with the join, which should give you the expected results:
var ExistingGroupDataSource = (from ppatg in dbContext.XXXXXXXXX
join pd1 in dbContext.XXXXXXXXXXX.Where(p => !p.GroupId.HasValue) on ppatg.ScheduleID equals pd1.ScheduleID
select
new
{
FinishPDI = pd1.ProductionDateID,
FinishingDate = pd1.WorkFlowDate,
ppatg.GroupName,
ppatg.PNTGroupID
});
I am converting some SQL queries to Linq (Entity Framework). Most of queries are working fine, but I am facing little problem with the following one.
When I try this query in SQL Server Management Studio, it returns multiple records.
SELECT
bDrillDown,
Icon
FROM
dbo.Checklist
INNER JOIN
dbo.Codes ON Checklist.iCodeID = Codes.iCodeID
AND Codes.bDeleted = 0 AND Codes.bObsolete = 0
INNER JOIN
dbo.CodeGroup ON Codes.iGroupID = CodeGroup.iGroupID
AND CodeGroup.bDeleted = 0 AND CodeGroup.bInspection = 1
INNER JOIN
dbo.CodeInspectionTypeV ON Cast(LEFT(Checklist.LongKey, 6) as int) = CodeInspectionTypeV.InspectionTypeID
WHERE
Checklist.bDeleted = 0
ORDER BY
iChecklistID
When I convert it into LINQ query like:
var checkList = from checklist in db.Checklists
join code in db.Codes on checklist.iCodeID equals code.iCodeID
where code.bDeleted == false && code.bObsolete == false
join codeGroup in db.CodeGroups on code.iGroupID equals codeGroup.iGroupID
where codeGroup.bDeleted == false && codeGroup.bInspection == true
join codeInspectionType in db.CodeInspectionTypeVs on checklist.LongKey.Substring(0, 6) equals codeInspectionType.InspectionTypeID.ToString()
where checklist.bDeleted == false
orderby checklist.iChecklistID
select new
{
checklist.iChecklistID,
InspectionTypeID = checklist.LongKey.Substring(0, 6).ToString()
};
It does not return any records, only an empty array.
The problem is apparently in the following join condition
on checklist.LongKey.Substring(0, 6) equals
codeInspectionType.InspectionTypeID.ToString()
which is not equivalent to the SQL query one.
Unfortunately EF does not support string to numeric data conversions, so your attempt is good, but doesn't work when the string value contains leading zeroes as in your case.
To make it work, you need to left pad with zeroes the result of the codeInspectionType.InspectionTypeID.ToString(), which can be done (at least in the latest EF6.1.3) by using the DbFunctions.Right canonical function (similar to how to sort varchar column containing numeric values with linq lambdas to Entity):
on checklist.LongKey.Substring(0, 6) equals
DbFunctions.Right("00000" + codeInspectionType.InspectionTypeID, 6)
Try to add "into [an alias name]" at the end of join line.
After that add a from line using that alias name
after that use that alias name in the where line
from checklist in db.Checklists
join code in db.Codes on checklist.iCodeID equals code.iCodeID into Temp1
from t1 in Temp1
where t1.bDeleted == false && t1.bObsolete == false
Could somebody help me please to convert this sql code to linq .
SQL query
select distinct coursecode
from UnitSet_Unit
where UnitCode in ('FDFFSACA' ,'FDFFSCFSAA', 'FDFOPTHCP3A ')
and CourseCode in (Select distinct coursecode
from Trainee_course
where TraineeID =10000088 )
Where UnitCode in IN clause come dynamic and in the form of array .
and the course code in the second part is also have variable count
Off the top of my head, assuming we have the following inputs (and you are working in C#):
var unitCodes = new List<string> { "FDFFSACA" ,"FDFFSCFSAA", "FDFOPTHCP3A" };
var traineeID = 10000088;
This should work:
var result = (from us in db.UnitSet_Unit
where unitCodes.Contains(us.UnitCode)
&& us.CourseCode == (from tc in db.Trainee_course
where tc.TraineeID == traineeID
select tc.CourseCode).Distinct().SingleOrDefault()
select us.CourseCode).Distinct();
Is there an easy way to do the following Nhibernate Linq statement
var query = from r in myTable.Query<MyTable>()
where r.Child == null
select r
The linq query above produces something similar to
SELECT MyTable.Id FROM MyTable WHERE MyTable.ChildId is null
it doesn't reference the child table and check if the left join is null like the following
SELECT MyTable.Id FROM MyTable
LEFT JOIN ChildTable ON MyTable.ChildId = ChildTable.Id
WHERE ChildTable.Id is null
var query = from r in myTable.Query<MyTable>()
where r.Child.Id == null
select r
I have a SQL database that I'm using LINQ to connect to (LINQ To SQL) and a local set of XML data (in a dataset). I need to perform an outer left join on the SQL table "tblDoc" and dataset table "document" on the keys "tblDoc:sourcePath, document:xmlLink". Both keys are unfortunately strings. The code I have below doesn't return any results and I've tried a few variations but my LINQ skills are limited. Does anyone have any suggestions or alternate methods to try?
DataColumn xmlLinkColumn = new DataColumn(
"xmlLink",System.Type.GetType("System.String"));
xmlDataSet.Tables["document"].Columns.Add(xmlLinkColumn);
foreach (DataRow xmlRow in xmlDataSet.Tables["document"].Rows)
{
xmlRow["xmlLink"] = (string)xmlRow["exportPath"] +
(string) xmlRow["exportFileName"];
}
var query =
from t in lawDataContext.tblDocs.ToList()
join x in xmlDataSet.Tables["Document"].AsEnumerable()
on t.SourceFile equals (x.Field<string>("xmlLink"))
select new
{
lawID = t.ID,
xmlID = x == null ? 0 : x.Field<int>("id")
};
foreach (var d in query.ToArray())
{
Debug.WriteLine(d.lawID.ToString() + ", " + d.xmlID.ToString());
}
The join clause produces standard inner join behavior. To get an outer join, you need to use the DefaultIfEmpty() extension method:
var query = from t in lawDataContext.tblDocs.ToList()
join x in xmlDataSet.Tables["Document"].AsEnumerable()
on t.SourceFile equals (x.Field<string>("xmlLink"))
into outer
from o in outer.DefaultIfEmpty()
select new
{
lawID = t.ID,
xmlID = o == null ? 0 : o.Field<int>("id")
};