Unable to Convert Linq to Lambda Notation - c#

public ActionResult EditArticle(int id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var typeId = 0;
var catId = 0;
var subCatId = 0;
var viewModel = (from sa in ems.SupportArticles
join ssc in ems.SupportSubCategories on sa.SubCatID equals ssc.SubCatID
join sc in ems.SupportCategories on ssc.CatID equals sc.CatID
join st in ems.SupportTypes on sc.TypeID equals st.TypeID
where sa.ArcticleId == id
select new SupportArticleViewModel { supportArticle = sa, supportSubCat = ssc, supportCat = sc, supportType = st });
foreach (var vm in viewModel)
{
typeId = vm.supportType.TypeID;
catId = vm.supportCat.CatID;
subCatId = vm.supportSubCat.SubCatID;
}
I want to convert it into Lambda Notation.But, I am unable to do it.Please help.I am using SupportViewModel which contains property of SupportType,SupportCategory ,SupportSubCategoryand SupportArticle.

Following is functional way do query , you have to make use of join function and than you get data
var filteredArtciles = SupportArticles.Where(sa=> sa.ArcticleId == id);
var query =
SupportArticles.
Join(SupportSubCategories,sa => sa.SubCatID ,ssc => ssc.SubCatID,(sa, ssc) => new {sa,ssc}).
Join(SupportCategories,sassc => sassc.ssc.CatID ,sc=>sc.CatID ,(sassc, sc) => new {sassc,sc}).;
Join(SupportTypes,sasscsc => sasscsc.sc.TypeID ,st=>st.TypeID ,(sc, st) => new {sasscsc,st}).
Select(j=>
new SupportArticleViewModel
{
supportArticle = j.sasscsc.sassc.sa,
supportSubCat = j.sasscsc.sassc.ssc,
supportCat = j.sasscsc.sc,
supportType = j.st
}
));

Related

Cannot convert from 'System.Collections.Generic.List' to System.Collection.Generic.IEnumerable

Here is the code:
[HttpGet]
public async Task<IActionResult> Get([FromQuery] string sort, [FromQuery] string sortColumn, [FromQuery] int perPage = 10, [FromQuery] int page = 0)
{
string searchString = string.Empty;
var ncquery = _context.NonConformities .AsQueryable();
var ncfilter = Helper.OrderBy(ncquery, sortColumn, sort == "asc")
.Skip(perPage * (page - 1))
.Take(perPage);
if (!String.IsNullOrEmpty(searchString))
{
ncfilter = ncfilter.Where(nc => nc.Title.Contains(searchString));
}
var data = await (from nc in _context.NonConformities
join mdt in _context.MasterData on nc.NcTypes equals mdt.Id
join mdo in _context.MasterData on nc.Originator equals mdo.Id
join mdd in _context.MasterData on nc.Department equals mdd.Id
join mdc in _context.MasterData on nc.Category equals mdc.Id
join mds in _context.MasterData on nc.Status equals mds.Id
select new
{
Id = nc.Id,
Title = nc.Title,
Originator = mdo.Items,
Department = mdd.Items,
Date = nc.Date,
NcTypes = mdt.Items,
Category = mdc.Items,
Status = mds.Items,
Description = nc.Description,
Evidence = nc.Evidence,
ReviewRecommendation = nc.ReviewRecommendation,
}).ToListAsync();
//await ncfilter.ToListAsync();
var totalItems = await _context.NonConformities.CountAsync();
int totalPages = (int)Math.Ceiling(totalItems / (double)perPage);
var model = new PaginatedItems<NonConformity>(page, perPage, totalPages, data );
return Ok(model);
}
I suspect the issue is in the line
var model = new PaginatedItems<NonConformity>(page, perPage, totalPages, data );
You need to have a list of NonConformity instead of a list of anonymous type:
select new
{
Id = nc.Id,
...
})
.ToListAsync() // Fetch the records from the database
.Select( x => new NonConformity(...)); // Transform them into NonConformity objects

LINQ to Entities does not recognize the method 'StaticMethod' method

I have a code like this:
using (var ws = new WebService())
using (var db = new EntityFrameworkModel())
{
var originalFolders = ws.GetFolders();
foo.folders = originalFolders.Select(c => new FolderType()
{
Id = c.Description,
Items = ws.ListDocs(c.Id)
.Select((d, i) =>
new DocType()
{
Id = StaticMethod(d, c),
Order = i,
SomeValue = db.docs.Single(doc => doc.Id == StaticMethod(d, c)).SomeValue
}
).ToArray()
}).ToArray();
}
But I get a "LINQ to Entities does not recognize the method 'StaticMethod' method, and this method cannot be translated into a store expression" exception. Does exist any way to pass a static value as a parameter? Something like this:
using (var ws = new WebService())
using (var db = new EntityFrameworkModel())
{
var originalFolders = ws.GetFolders();
foo.folders = originalFolders.Select(c => new FolderType()
{
Id = c.Description,
Items = ws.ListDocs(c.Id)
.Select((d, i, string myValue = StaticMethod(d, c)) =>
new DocType()
{
Id = myValue,
Order = i,
SomeValue = db.docs.Single(doc => doc.Id == myValue).SomeValue
}
).ToArray()
}).ToArray();
}
I can't modify DocType class constructor. Does exist any way?
Usually this is a matter of making sure you don't inline functions in linq-to-SQL expressions that can't be turned into valid SQL.
Try this:
using (var ws = new WebService())
using (var db = new EntityFrameworkModel())
{
var originalFolders = ws.GetFolders();
foo.folders = originalFolders.Select(c => new FolderType()
{
Id = c.Description,
Items = ws.ListDocs(c.Id)
.Select((d, i) =>
{
var id = StaticMethod(d, c);
return new DocType()
{
Id = id,
Order = i,
SomeValue = db.docs.Single(doc => doc.Id == id).SomeValue
};
}).ToArray()
}).ToArray();
}

Entity Framework Core - (Kind of subquery)

I use fluent API and Ef Core.
This is my linq:
var data = (from candidateHP in _cempContexto.CandidateHiringProcessSummary
join jobsHP in _cempContexto.JobHiringProcessSummary on candidateHP.JobCode equals jobsHP.JobCode
join job in _cempContexto.Vaga on jobsHP.JobCode equals job.Codigo
join candidateJob in _cempContexto.TrCandidatoVaga on new { X = job.Codigo, Y = candidateCode } equals new { X = candidateJob.VagaCodigo, Y = candidateJob.CandidatoCodigo }
where
candidateHP.CandidateCode == candidateCode
select
new
{
JobCode = jobsHP.JobCode,
CompanyCode = job.EmpresaCodigo,
Title = job.Titulo,
HasImage = true,
CompanyName = job.NomeEmpresa,
QuantityJobs = job.QuantidadeVaga,
Location = job.CidadeCodigo,
QuantityResumeSent = jobsHP.QuantityResumeSent,
JobStatusCode = jobsHP.StatusCode,
CandidateStatusCode = candidateHP.StatusCode,
StatusCode = job.StatusCodigo,
ResumeSentDate = candidateJob.Data,
InsertDate = job.DataDeCadastro,
EndDate = job.DataDeSaida,
city= _cempContexto.TrVagaCidade.SelectMany(p => _cempContexto.TrVagaCidade.Where(q => q.VagaCodigo == candidateHP.JobCode).Select(q => new { q })).ToList()
})
.ToList();
I need to Fill city with that subquery. I need a better way to do that, How could I proceed?
Split code into two queries :
var query = (from candidateHP in _cempContexto.CandidateHiringProcessSummary
join jobsHP in _cempContexto.JobHiringProcessSummary on candidateHP.JobCode equals jobsHP.JobCode
join job in _cempContexto.Vaga on jobsHP.JobCode equals job.Codigo
join candidateJob in _cempContexto.TrCandidatoVaga on new { X = job.Codigo, Y = candidateCode } equals new { X = candidateJob.VagaCodigo, Y = candidateJob.CandidatoCodigo }
where
candidateHP.CandidateCode == candidateCode
select
new
{ jobsHP = jobsHP, job = job, candidateJob = candidateJob}).ToList();
var data = query.Select(x => new {
JobCode = x.jobsHP.JobCode,
CompanyCode = x.job.EmpresaCodigo,
Title = x.job.Titulo,
HasImage = true,
CompanyName = x.job.NomeEmpresa,
QuantityJobs = x.job.QuantidadeVaga,
Location = x.job.CidadeCodigo,
QuantityResumeSent = x.jobsHP.QuantityResumeSent,
JobStatusCode = x.jobsHP.StatusCode,
CandidateStatusCode = x.candidateHP.StatusCode,
StatusCode = x.job.StatusCodigo,
ResumeSentDate = x.candidateJob.Data,
InsertDate = x.job.DataDeCadastro,
EndDate = x.job.DataDeSaida,
city= query.Select(y => y.candidateHP.JobCode).Select(q => new { q })).ToList()
})
.ToList();

How Querying with EDM LINQ Method?

How this LINQ Query syntax:
var city = from c in _db.SubCategories where c.KategorijaID == stateID select new { c.PodKategorijaID, c.NazivPodKategorije };
change to LINQ Method syntax?
Example
This is LINQ Query syntax:
using (var context = new SchoolDBEntities())
{
var L2EQuery = from st in context.Students
where st.StudentName == "Bill"
select st;
var student = L2EQuery.FirstOrDefault<Student>();
}
and this is LINQ Method syntax:
//Querying with LINQ to Entities
using (var context = new SchoolDBEntities())
{
var L2EQuery = context.Students.where(s => s.StudentName == "Bill");
var student = L2EQuery.FirstOrDefault<Student>();
}
var city = _db.SubCategories.Where(c => c.KategorijaID == stateID)
.Select(c => new { c.PodKategorijaID, c.NazivPodKategorije });
var city = _db.SubCategories.Where(c => c.KategorijaID == stateID)
.Select(c => new { c.PodKategorijaID, c.NazivPodKategorije });

linq join, group by to get count of child table

After getting my join to work I seem to have gotten stuck on the count bit.
What I am attempting below is get a count of documents printed based on the join below.
What would the code be to get the count per 'guardiandocsrequired'?
var guardianEntityType = new {EntityTypeFK = "GUARDIAN"};
return (from d in dbContext.GuardianDocsRequireds
join p in dbContext.DocumentPrintingLogs on
new { docTypeFK = d.DocTypeFK, entityFK = d.GuardianFK } equals
new { docTypeFK = p.DocTypeFK, entityFK = p.EntityFK }
where d.GuardianFK == entityPK && p.ItemGroupFK == itemGroupID && p.EntityTypeFK == "GUARDIAN"
group d by new
{
d.GuardianFK,
d.DocTypeFK,
d.DocumentType.DocTypeDescription,
d.RequiredStatus
}
into res
select new DocumentsRequired
{
EntityPK = res.Key.GuardianFK,
EntityType = entityType,
DocTypeFK = res.Key.DocTypeFK,
DocTypeDescription = res.Key.DocTypeDescription,
RequiredStatus = res.Key.RequiredStatus,
PrintCount = ???
}
).ToList();
If it helps, I have written the sql to produce exactly what I require as follows:
SELECT gdr.DocRequiredID,gdr.RequiredDate,gdr.GuardianFK,gdr.DocTypeFK,gdr.RequiredStatus,
COUNT(dpl.DocPrintedID) AS documentsPrinted
FROM dbo.GuardianDocsRequired gdr
LEFT OUTER JOIN dbo.DocumentPrintingLog dpl ON gdr.DocTypeFK = dpl.DocTypeFK
AND gdr.GuardianFK = dpl.EntityFK
AND dpl.EntityTypeFK = 'GUARDIAN'
WHERE gdr.GuardianFK = #entityPK
GROUP BY gdr.DocRequiredID,gdr.RequiredDate,gdr.GuardianFK,gdr.DocTypeFK,gdr.RequiredStatus
Do you mean sth like this?
var guardiandocsrequired = (from d in dbContext.GuardianDocsRequireds
join p in dbContext.DocumentPrintingLogs on
new { docTypeFK = d.DocTypeFK, entityFK = d.GuardianFK } equals
new { docTypeFK = p.DocTypeFK, entityFK = p.EntityFK }
where d.GuardianFK == entityPK && p.ItemGroupFK == itemGroupID && p.EntityTypeFK == "GUARDIAN"
group d by new
{
d.GuardianFK,
d.DocTypeFK,
d.DocumentType.DocTypeDescription,
d.RequiredStatus
}
into res
select new DocumentsRequired
{
EntityPK = res.Key.GuardianFK,
EntityType = entityType,
DocTypeFK = res.Key.DocTypeFK,
DocTypeDescription = res.Key.DocTypeDescription,
RequiredStatus = res.Key.RequiredStatus,
PrintCount = ???
}
).ToList();
int cnt = guardiandocsrequired.Count;
return guardiandocsrequired;

Categories

Resources