I have a simple SQL Query which I'm trying to translate to linq. But I keep getting
"...is not supported"
The Query is:
SELECT HARDWARE_ID, HWName, HWTyp_FK from T_HARDWARE
left join T_SWInstalled on T_HARDWARE.HARDWARE_ID = T_SWInstalled.SIHardware_FK
and SISWVerzeichnis_FK = 213
where SWInstalled_id is null
My try with linq:
var cni = from hardware in _context.T_HARDWARE
where hardware.T_SWInstalled.Where(si => si.SISWVerzeichnis_FK == _softwareId) == null
select new InstalledOnListItem(hardware.HARDWARE_ID, hardware.HWName);
Is this actually only possible with raw SQL? Thanks
Use join syntax:
var query =
from hardware in _context.T_HARDWARE
join sw in _context.T_SWInstalled
on new {
JoinProperty1 = hardware.HARDWARE_ID,
JoinProperty2 = sw.SISWVerzeichnis_FK
}
equals
new {
JoinProperty1 = sw.SIHardware_FK,
JoinProperty2 = 213
}
where sw.SWInstalled_id == null
select new InstalledOnListItem(hardware.HARDWARE_ID, hardware.HWName);
Related
Here I have SQL query, now I am trying to translate it into linq but don't have any idea how to do it and got stuck in getting ChapterId from ChapterQuestion table.
Any help with translation will be grate.
Thank you
Below is my sql query
SELECT CQ.ChapterId,CQS.SetNumber,count(distinct CQ.ChapterQuestionId) as questioncount FROM
[dbo].[ChapterQuestion] AS CQ
JOIN [dbo].[ChapterQuestionSet] AS CQS ON CQ.ChapterQuestionSetId = CQS.ChapterQuestionSetId
WHERE CQ.ChapterId = 1 group by CQS.SetNumber,CQ.ChapterId
Below is my linq
var list = (from CQS in uow.Repository<ChapterQuestionSet>().GetAll().ToList()
join CQ in uow.Repository<ChapterQuestion>().FindBy(x => x.ChapterId == chapterId).ToList()
on CQS.ChapterQuestionSetId equals CQ.ChapterQuestionSetId
group CQ by CQS into G1
select new ChapterQuestionSetVM
{
ChapterQuestionSetId = G1.Key.ChapterQuestionSetId,
Count = G1.Count(t => t.ChapterQuestionSetId != null),
QuestionSetNo = $"Question set {G1.Key.SetNumber}",
ChapterId = // how do i get chapterid from ChapterQuestion
}).ToList();
This is corrected query. I hope Repository.GetAll() returns IQueryable?
This query works only with EF Core 5.x
var query =
from CQS in uow.Repository<ChapterQuestionSet>().GetAll()
join CQ in uow.Repository<ChapterQuestion>().GetAll() on CQS.ChapterQuestionSetId equals CQ.ChapterQuestionSetId
where CQ.ChapterId == 1
group CQ by new { CQS.SetNumber, CQ.ChapterId } into G1
select new ChapterQuestionSetVM
{
ChapterId = G1.Key.ChapterId
QuestionSetNo = $"Question set {G1.Key.SetNumber}",
Count = G1.Select(t => t.ChapterQuestionSetId).Distinct().Count(),
};
var list = query.ToList();
I converted sql query to linq query without any error.
Now, my question is that I get the data properly in sql query, while in linq query showing the whole data without filtering product null.
Here is my code:
SQL Query
SELECT Name
FROM ProductMaster product
LEFT JOIN TouchWastageGroup touchWastageGroup ON touchWastageGroup.Product = product.Name and touchWastageGroup.GroupNameId = 2 and touchWastageGroup.CaratId = 6
WHERE touchWastageGroup.Product IS NULL
From this query data showing properly.
Linq Query
var productSelected = (from product in _productMasterRepository.Table
from touchWastageGroup in _touchWastageGroupRepository.Table
.Where(touchWastageGroup => touchWastageGroup.Product == product.Name && touchWastageGroup.GroupNameId == 2 && touchWastageGroup.CaratId == 6)
.DefaultIfEmpty().Where(x => x.Product == null)
select new
{
Result = product.Name
}).ToList();
Same query of linq showing whole data without filtering this (Where(x => x.Product == null)).
Is there a problem in linq syntax or in query?
Check with following query to return which has no product
from product in _productMasterRepository.Table
join touchWastageGroup in _touchWastageGroupRepository.Table on new { Product = product.Product, GroupNameId = 2, CaratId = 6 } equals new { touchWastageGroup.Product, touchWastageGroup.GroupNameId, touchWastageGroup.CaratId } into joinedResult
from touchWastageGroup in joinedResult.DefaultIfEmpty()
where touchWastageGroup == null
select new { Result = product.Name }
Try to use this query
var productSelected = from product in _productMasterRepository.Table
join from touchWastageGroup in _touchWastageGroupRepository.Table on
product.Name equals touchWastageGroup.Product into temp
from t in temp.DefaultIfEmpty()
where t.GroupNameId == 2 && t.CaratId == 6
select new
{
Result = product.Name
}).ToList();
I have 3 tables
- ERPEntry
- ERPEntryType
- ERPApp
I am trying to get data from these 3 tables using the below query but i got the error :
specified linq expression contains references to queries that are
associated with different contexts
var erpEntryInfo = (from s in ERPDB.ERPEntrys
JOIN t in ERPDB.ERPEntryTypes
on s.EntryTypeID equals t.EntryTypeID
join a in APPDB.ERPApps
on s.AppId equals a.AppId
where s.UserIDAdded == '250176'
select new ERPInfo
{
EntryId = s.EntryID,
EntryType = t.EntryTypeName,
ERPApp = a.ApplicationName,
DateAdded = s.DateAdded
}).OrderByDescending(d => d.DateAdded).Take(10).ToList();
I searched based on the errror and tried to split the above query into 2 as below.
var res = (from s in ERPDB.ERPEntrys
join t in ERPDB.ERPEntryTypes
on s.EntryTypeID equals t.EntryTypeID
where s.UserIDAdded == '250176'
select new {s.EntryTypeID, s.DateAdded, t.EntryTypeName, s.AppID }).OrderByDescending(d => d.DateAdded).Take(10).ToArray();
var y = (from a in APPDB.ERPApps
join b in res on a.AppId equals //??//
select new ERPInfo
{
EntryId = b.EntryID,
EntryType = b.EntryTypeName,
ERPApp = a.ApplicationName,
DateAdded = b.DateAdded
}).ToList();
I am having an issue in the above query to access AppId which i got into the result res..i commented with //??// in the above code
can i get any help on this.
How can I convert this SQL Server stored procedure to a linq expression? I've got a couple of mistakes but don't know how to fix them.
Here is the stored procedure:
#MatterNumber NVARCHAR(20)
AS
DECLARE #ClientNumber INT = (SELECT TOP 1 LeadPlaintiffNumber
FROM [dbo].[vw_cmp_case_numbers]
WHERE MatterNumber = #MatterNumber)
SELECT DISTINCT
defendantid,
defendantcode,
defendantname DefendantName
FROM
(SELECT DISTINCT
fmrp.employerid DefendantId,
fmrp.employercode DefendantCode,
fmrp.employername DefendantName
FROM
vw_mpid_records fmr
LEFT JOIN
vw_mpid_records_products fmrp ON fmr.recordid = fmrp.recordid
INNER JOIN
vw_cmp_event_history fceh ON fmr.jobsitecode = fceh.jobsitecode
AND fmr.startdate < = fceh.enddate
WHERE
fceh.clientnumber = #ClientNumber
AND fmrp.employerid IS NOT NULL
AND fmrp.employercode IS NOT NULL
GROUP BY
fmrp.employerid, fmrp.employercode, fmrp.employername) yyy
ORDER BY
defendantname
Here is what I have so far for the linq but there is a error at
fmr.StartDate <= fceh.EndDate
and then I'm not sure about the group by as well
var #clientNumber = (from ccn in context.VwCmpCaseNumbers where ccn.MatterNumber == text select ccn).Take(1);
var innerQuery = from fmr in context.VwMpidRecords
join fmrp in context.VwMpidRecordsProducts on fmr.Id equals fmrp.Id
into gj
from x in gj.DefaultIfEmpty()
join fceh in context.VwCmpEventHistorys on fmr.JobsiteCode equals fceh.JobsiteCode && fmr.StartDate <= fceh.EndDate
where fceh.ClientNumber = #clientNumber &&
fmrp.EmployerID != null &&
fmrp.EmployerCode != null
group fmrp.by fmrp.EmployerID && fmrp.EmployerCode && fmrp.EmployerName
var outerQuery = (from r in innerQuery
select new
{
EmployerId = r.EmployerID,
EmployerCode = r.EmployerCode,
EmployerName = r.EmployerName
}).OrderBy(obj => obj.DefendantName);
var viewModel = outerQuery.Select(obj => new SelectOption
{
Text = obj.DefendantCode,
Value = obj.DefendantId,
});
Here are the lines that show the errors
LINQ doesn't allow you to "join" on any criteria you want: a join can only have a [this] equals [that] form. Move any criteria that doesn't match that pattern into a where clause. (This will not impact performance of the SQL query.)
Also, group by values need to be contained in a single (anonymous) object, not &&ed together.
var innerQuery = from fmr in context.VwMpidRecords
join fmrp in context.VwMpidRecordsProducts
on fmr.Id equals fmrp.Id
join fceh in context.VwCmpEventHistorys
on fmr.JobsiteCode equals fceh.JobsiteCode
where fmr.StartDate <= fceh.EndDate
where fceh.ClientNumber = #clientNumber
where fmrp.EmployerID != null && fmrp.EmployerCode != null
group fmrp by new {fmrp.EmployerID, fmrp.EmployerCode, fmrp.EmployerName};
I use Linqer to convert SQL to LinQ but result are not the same
My SQL query :
Select ChuyenNganh.ChuyenNganhID,ChuyenNganh.TenChuyenNganh,SoLuong= count(BaiBao.ChuyenNganhID )
from BaiBao right join ChuyenNganh on ChuyenNganh.ChuyenNganhID = BaiBao.ChuyenNganhID
group by ChuyenNganh.ChuyenNganhID, ChuyenNganh.TenChuyenNganh
Convert to Linq
var queryChuyenNganh = from t in myPhanLoaiTaiLieuDataContext.ChuyenNganhs
join t0 in myPhanLoaiTaiLieuDataContext.BaiBaos on new { ChuyenNganhID = t.ChuyenNganhID } equals new { ChuyenNganhID = Convert.ToInt32(t0.ChuyenNganhID) } into t0_join
from t0 in t0_join.DefaultIfEmpty()
group t by new
{
t.ChuyenNganhID,
t.TenChuyenNganh
} into g
select new
{
ChuyenNganhID = (System.Int32)g.Key.ChuyenNganhID,
g.Key.TenChuyenNganh,
SoLuong =(Int32)g.Count()
};
Result:
Linq
SQL
Who can fix it for me?
Most probably the SQL query can be rewritten in LINQ without group by but simple LINQ GroupJoin.
But the main issue with your conversion is that SQL COUNT(expr) does not count NULL values, and there is no direct LINQ equivalent, so either conditional Count or Sum is needed (I personally prefer the later because usually it translates to better SQL).
So, the minimum change needed in you query is
group t by new to group t0 by new
and SoLuong =(Int32)g.Count() to SoLuong = g.Sum(t0 => t0 != null ? 1 : 0)
P.S. As mentioned at the beginning, I would give a try to the following LINQ query:
var queryChuyenNganh =
from t in myPhanLoaiTaiLieuDataContext.ChuyenNganhs
join bb in myPhanLoaiTaiLieuDataContext.BaiBaos
on t.ChuyenNganhID equals bb.ChuyenNganhID into t_BaiBaos
select new
{
t.ChuyenNganhID,
t.TenChuyenNganh,
SoLuong = t_BaiBaos.Count()
};
The difference is that SQL counts non-null values in BaiBao.ChuyenNganhID, a column in the outer join table, while LINQ counts all records.
You need to make LINQ count non-null values as well:
var queryChuyenNganh = from t in myPhanLoaiTaiLieuDataContext.ChuyenNganhs
join t0 in myPhanLoaiTaiLieuDataContext.BaiBaos
on new { t.ChuyenNganhID } equals new { ChuyenNganhID = Convert.ToInt32(t0.ChuyenNganhID) } into t0_join
from t0 in t0_join.DefaultIfEmpty()
group new {T=t, NonNull=t0.ChuyenNganhID != null} by new
{
t.T.ChuyenNganhID,
t.T.TenChuyenNganh
} into g
select new
{
ChuyenNganhID = (System.Int32)g.Key.ChuyenNganhID,
g.Key.TenChuyenNganh,
SoLuong =(Int32)g.Count(x => x.NonNull)
};