How return linq query below this
public SewaPeralatan FindByNotaSewa(string notaSewa)
{
var dataSewa =
from sp in _context.SewaPeralatan
join spd in _context.SewaPeralatanDetails on sp.Id equals spd.SpId
where sp.NotaSewa == notaSewa
select new { sp, spd };
return dataSewa.FirstOrDefault();
}
the return get error like this
"Cannot implicitly convert type '<anonymous type: SYN.Models.SewaPeralatan sp, SYN.Models.SewaPeralatanDetail spd>' to 'SYN.Models.SewaPeralatan'"
What I expect from the return is to be able to get data from the SewaPeralatanDetail table
The SewaPeralatanDetail table contains details from the SewaPeralatan Table
if you are using EF you can use linq like this to return SewaParlatan
public SewaPeralatan FindByNotaSewa(string notaSewa)
{
var dataSewa =
_context.SewaPeralatan
.Where(b => b.NotaSewa == notaSewa)
.Include(b => b.SewaPeralatanDetails)
.FirstOrDefault();
return dataSewa;
}
Related
This code is from my sql query
SELECT Branchname
FROM Branch
WHERE NOT EXISTS (SELECT Branchname FROM vBranching
WHERE Branch.Branchname = vBranching.Branchname AND UserName = 'xCuttiepies');
iwant to execute it into linq c# web api
Its look like this
var Branch = _dbcontext.Branches.Select(c => c.Branchname).ToList();
var vBranching = _dbcontext.VBranchings.Select(a => a.BranchName).ToList();
var ass = Branch.Where(!Branch.Exists(Branch == vBranching));
return Ok(vBranching);
In Branch == vBranching it says cannot convert from bool to System.Predicate<string>
I want to fetch the data that not exists on that different tables.
You souldn't be using ToList except right at the end, and your lambda syntax is off, and the equivalent of EXISTS is Any. You are also returning the wrong value.
var Branches =
_dbcontext.Branches
.Where(b => !_dbcontext.VBranchings.Any(vb =>
vb.BranchName == b.BranchName && vb.UserName == "xCuttiepies"))
.Select(c => c.Branchname)
.ToList();
return Ok(Branches);
I have the following linq query:
var fileDocuments = (
from doc in fileUploads
from invoice in
(
from inv in _dbContext.SupplierInvoiceHeaders
where inv.InvoiceDocumentId == doc.ID || inv.JobSheetInvoiceId == doc.ID
select inv
).DefaultIfEmpty()
join pos in _dbContext.PurchaseOrders on invoice.PurchaseOrder.PurchaseOrderId equals pos.PurchaseOrderId into poss
from po in poss.DefaultIfEmpty()
join hdf in _dbContext.HelpDeskFaults on po.HelpdeskFaultId equals hdf.ID into hdfpo
from hs in hdfpo.DefaultIfEmpty()
join store1 in _dbContext.Stores on hs.StoreID equals store1.ID into hsf
from hdfStore in hsf.DefaultIfEmpty()
join js in _dbContext.JobSheets on invoice.SupplierInvoiceHeaderId equals js.SupplierInvoiceHeaderID into jss
from jobSheets in jss.DefaultIfEmpty()
join ch in _dbContext.ChildProjects on po.ChildProjectId equals ch.ID into chs
from childProjects in chs.DefaultIfEmpty()
join ph in _dbContext.ProjectHeaders on childProjects.ProjectHeaderID equals ph.ID into phs
from projectHeaders in phs.DefaultIfEmpty()
join ppmsl in _dbContext.PpmScheduleLines on projectHeaders.PPMScheduleRef equals ppmsl.ID into ppsmsls
from ppmScheduleLines in ppsmsls.DefaultIfEmpty()
join ss2 in _dbContext.Stores on ppmScheduleLines.StoreID equals ss2.ID into ssts
from store2 in ssts.DefaultIfEmpty()
where getJobWhereClause(invoice, hs, ppmScheduleLines, doc)
select new
{
doc.ID,
JobSheetId = jobSheets.DocumentID,
doc.Name,
doc.DateCreated,
doc.StoreID,
StoreName = doc.Store.Name,
DocumentType = doc.DocumentType.Name,
doc.DocumentTypeID
})
.AsEnumerable()
.Distinct()
.Select(d => new JobDocumentDto
{
ID = d.ID,
DocumentID = (d.JobSheetId) ?? d.ID,
DocumentName = d.Name,
DateCreated = d.DateCreated.ToString("dd/MM/yyyy"),
StoreName = d.StoreName,
DocumentTypeName = d.DocumentType,
DocumentTypeId = d.DocumentTypeID
}).OrderByDescending(x => x.ID);
return fileDocuments;
I have tried to separate the where clause into a func:
Func<SupplierInvoiceHeader, HelpDeskFault, PpmScheduleLineEntity, DocumentUploadEntity, bool> getJobWhereClause = (invoice, helpDeskFault, ppmScheduleLine, doc) =>
{
if (!string.IsNullOrEmpty(jobSearchParams.PIR) && string.IsNullOrEmpty(jobSearchParams.StoreName))
{
return invoice.PurchaseInvoiceReference == jobSearchParams.PIR;
}
if (string.IsNullOrEmpty(jobSearchParams.PIR) && !string.IsNullOrEmpty(jobSearchParams.StoreName))
{
return helpDeskFault.Store.Name.Contains(jobSearchParams.StoreName) || doc.Store.Name.Contains(jobSearchParams.StoreName) || ppmScheduleLine.Store.Name.Contains(jobSearchParams.StoreName);
}
return invoice.PurchaseInvoiceReference == jobSearchParams.PIR && (helpDeskFault.Store.Name.Contains(jobSearchParams.StoreName) || doc.Store.Name.Contains(jobSearchParams.StoreName) || ppmScheduleLine.Store.Name.Contains(jobSearchParams.StoreName));
};
I get the following error message:
Test method
IntegrationTests.Services.DocumentUploadServiceTests.Should_Search_By_PIR
threw exception: System.NotSupportedException: The LINQ expression
node type 'Invoke' is not supported in LINQ to Entities.
Which makes sense because there is no direct translation from the func to sql but is there a way I can create an expression that will achieve what I am after?
The easiest way is just to use an extension method and return an IQueryable, something like this (just fill in the ...):
public static IQueryable<fileUpload> FilterByThisStuff(this DbSet<fileUpload> db, ... invoice, ... helpDeskFault, ... ppmScheduleLine, ... doc)
{
if (!string.IsNullOrEmpty(jobSearchParams.PIR) && string.IsNullOrEmpty(jobSearchParams.StoreName))
{
return db.Where(invoice=>invoice.PurchaseInvoiceReference == jobSearchParams.PIR);
}
if (string.IsNullOrEmpty(jobSearchParams.PIR) && !string.IsNullOrEmpty(jobSearchParams.StoreName))
{
return db.Where(...);
}
return db.Where(...);
};
I've noticed you have an awful lot of joins there. Consider actually building your model with navigation properties instead. In anycase you can then use the above just like any other LINQ method, otherwise you will need to make some concrete class so you can use it in the extension method. The easy way:
var results=db.FileUploads
.FilterByThisStuff(a,b,c,d)
.Select(...)
.OrderBy(...)
.Take(...);
I'm trying to do a LINQ statement using three database tables for my third dropdownlist. Below are my codes but I get an error (for my third dropdownlist) when I choose a cluster in the second dropdownlist.
**//SECTORS**
public JsonResult GetSectors()
{
using (SAMPDBEntities context = new SAMPDBEntities())
{
var ret = context.SECLIBs
.Select(x => new { x.seccd, x.unitacro }).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
**//CLUSTERS**
public JsonResult GetCluster(string seccd)
{
using (SAMPDBEntities context = new SAMPDBEntities())
{
var ret = context.CLUSLIBs
.Where(x => x.seccd.Contains(seccd))
.Select(x => new { x.cluscd, x.unitdesc }).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
**//EMPLOYEES**
public JsonResult GetEmployee(string cluscd)
{
using (SAMPDBEntities context = new SAMPDBEntities())
{
var ret = context.UNILIBs
.Where(a => a.cluscd.Contains(cluscd))
.Include(x => x.PPSAs.Select(y => y.EMPFILE.empno))
.ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
Here's my error:
A specified Include path is not valid. The EntityType 'SAMPDBModel.EMPFILE' does not declare a navigation property with the
name 'empno'.
and here's the SQL query (for my third dropdownlist):
SELECT DISTINCT e.empno, e.lname, e.fname, e.mname, c.cluscd
FROM SECLIB a
INNER JOIN CLUSLIB b
ON a.seccd = b.seccd
INNER JOIN UNILIB c
ON b.cluscd = c.cluscd
INNER JOIN PPSA d
ON c.unitcode = d.unitcd
INNER JOIN EMPFILE e
ON d.empno = e.empno
WHERE e.empstat = 1 AND c.cluscd = #cluscd
I need to do a cascading dropdownlist and I need to show the list of employees based on the selected sector and cluster. How can I do that using multiple tables? Please help me. Thanks in advance!
This should be an issue of not specifying the correct respective name that generated from EDMX. Please Can you check the "EMPFILE" Class that generated from Entity Framework It should have similar name with different case sensitive word.
When querying in SQL it does not bother with case sensitivity. But C# is case sensitive language.
And its better if you can post the "EMPFILE" class and database table here.
List<VideoInfo> vobj = new List<VideoInfo>();
vobj = (from vid in db.VideoInfoes.Where(c => c.IsActive == true)
orderby vid.VideoId descending
select vid
).ToList();
return View(vobj);
This is the orignal Query to bring the list of all the video info.
There is another table called profile which has the Profile Picture which I need along with the video Info.
So after going through an article on EF I came up with some thing like this..
vobj = (from vid in db.VideoInfoes.Where(c => c.IsActive == true)
select new
{
ProfileId = vid.ProfileId,
ProfilePictureUrl = vid.ProfileInfo.ProfilePictureUrl
}
orderby vid.VideoId descending
select vid
).ToList();
return View(vobj);
ProfileId is the foreign key. But this is not even compiling..Its showing red syntax error after the closing curly brackets and orderby.
You should do OrderBy before Select since the property you want to order is not contained in your new select:
var vobj = (from vid in db.VideoInfoes.Where(c => c.IsActive == true)
orderby vid.VideoId descending
select new
{
ProfileId = vid.ProfileId,
ProfilePictureUrl = vid.ProfileInfo.ProfilePictureUrl
}
).ToList();
Aslo I feel more comfortable if using lambda syntax:
var vobj = db.VideoInfoes.Where(c => c.IsActive)
.OrderByDescending(c => c.VideoId)
.Select(c => new {
ProfileId = vid.ProfileId,
ProfilePictureUrl = vid.ProfileInfo.ProfilePictureUrl
}).ToList();
Your function can be corrected and made much simpler as follows:
return View(
db
.VideoInfoes
.Where(videoInfo => videoInfo.IsActive)
.OrderByDescending(videoInfo => videoInfo.VideoID)
.ToList());
You will be able to access the ProfileInfo of each VideoInfo in the list, so long as the db connection is not disposed. Or you can access other ProfileInfo records using the ProfileId property in another query with another context later. It depends what you would like to do with the data; (I'm not sure what the View function is doing, for example.)
For example:
// where 'data' was what was returned from the above query
// and assuming the above 'db' connection is still open
foreach (VideoInfo videoInfo in data)
{
ProfileInfo profileInfo = videoInfo.ProfileInfo;
// do something with profileInfo
}
// or if the connection was disposed:
using (MyEFModel db = new MyEFModel())
foreach (VideoInfo videoInfo in data)
{
int profileID = videoInfo.ProfileId;
ProfileInfo profileInfo =
db
.ProfileInfoes
.Single(row => row.ID == profileID);
// do something with profileInfo
}
I have a LINQ query works when I set the return value to a List, however I just want to return an IQueryable<Post>. How would I do that?
public List<Post> GetPostByID(int id)
{
var thePost = (from p in _context.Posts
where p.Id == id
select p).ToList();
return thePost;
}
public IQueryable<Post> GetPostByID(int id)
{
return (from p in _context.Posts
where p.Id == id
select p);
}
Naturally due to deferred execution, this query will be executed at the put the caller tries to enumerate the results.
var thePost = (from p in _context.Posts
where p.Id == id
select p);
return thePost;