LINQ query works on LINQPAD throws Error on Visual Studio - c#

var data = (from prod in db.ref_ProductAvail
group prod by new { prod.storeOfAccount, prod.serviceName } into g
orderby g.Key.storeOfAccount
join branch in db.ref_Branch
on g.Key.storeOfAccount equals branch.code
select new
{
branchCode = g.Key.storeOfAccount,
branchName = branch.description,
serviceName = g.Key.serviceName,
svcCount = g.Key.serviceName.Count()
}).ToList();
My Query works on LINQPAD but throws this error on C# >
DbExpressionBinding requires an input expression with a collection ResultType.Parameter name: input,
as I've searched for a solution I failed to found the exact solution to my problem, also removing ToList or using IEnumerable does work but I cannot use foreach.

Yes, you got it right. the error should be in g.Key.serviceName.Count() because this expression is trying to count number of characters in serviceName string. which is not convertible to sql. If you want to achieve the same thing, you can try something like
var data = (from prod in db.ref_ProductAvail
group prod by new { prod.storeOfAccount, prod.serviceName } into grouping
orderby grouping.Key.storeOfAccount
from g in grouping
join branch in db.ref_Branch
on g.Key.storeOfAccount equals branch.code
select new
{
branchCode = g.Key.storeOfAccount,
branchName = branch.description,
serviceName = g.Key.serviceName,
svcCount = grouping.Select(x=>x.Key.serviceName).Distinct().Count()
}).ToList();
Haven't tested it though

Related

{"LINQ to Entities does not recognize the method 'Boolean IsLetter(Char)' method, and this method cannot be translated into a store expression."}

I want to get all items in the database using LINQ where the Title starts with special characters or number, I already tried the code below but it's not working.
Thanks
result = (from asset in _db.Query<Asset>()
where !char.IsLetter(asset.Title[0])
select new AssociatedItem { Id = asset.AssetId, Title = asset.Title, Type = Constants.FeedbackTypes.ASSET }).ToList();
That's because char.IsLetter is not a dbFunction.
You can apply where after converting the results ToList()
result = (from asset in _db.Query<Asset>()
select new AssociatedItem { Id = asset.AssetId, Title = asset.Title, Type = Constants.FeedbackTypes.ASSET }).ToList()
.Where(a => !char.IsLetter(a.Title[0])).ToList();
PS: Try to identify some other where clause for the db query to limit the results.
I'd give the SqlMethods class from the System.Data.Linq.SqlClient namespace a shot.
result = (from asset in _db.Query<Asset>()
where !SqlMethods.Like(asset.Title, "[a-Z]%")
select
new AssociatedItem
{
Id = asset.AssetId,
Title = asset.Title,
Type = Constants.FeedbackTypes.ASSET
}).ToList();

Getting DISTINCT values from a JOIN

i currently have the following LINQ statement:
using (MYEntities ctx = CommonMY.GetMYContext())
{
List<datUser> lstC = (from cObj in ctx.datUser
join fs in ctx.datFS on cObj.UserID equals fs.datUser.UserID
where userOrg.Contains(fs.userOrg.OrgName)
select cObj).ToList();
foreach (datUser c in lstC)
{
Claim x = new Claim
{
UserID= c.userID,
FirstName = c.FirstName,
LastName = c.LastName,
MiddleName = c.MiddleName,
};
}
}
right now it returns all users, but it duplicates them if they have more then 1 org associated with them.
how can i ensure that it only returns distinct UserIDs?
each user can have multiple orgs, but i really just need to return users that have at least 1 org from the userOrg list.
Right before your ToList, put in .Distinct().
In response to #DJ BURB, you should probably use the Distinct overload that takes in an IEqualityComparer to best be sure that you're doing it based off of the unique id of each record.
Look at this blog post for an example.
use group by.
syntax:
var result= from p in <any collection> group p by p.<property/attribute> into grps
select new
{
Key=grps.Key,
Value=grps
}
You will have to call Distinct(), there is no linq query equivalent of that command.

Where In with nHibernate using InExpression

Having a really hard time trying to figure out a "where in" equivalent in nHibernate.
I am using nHibernate 3. What's the best way to do something like this:
SELECT DISTINCT
U.ID as CID
FROM User U
WHERE
CID IN (
SELECT RID
FROM ResellerSites rs
INNER JOIN Locations l ON l.ID = rs.LID
WHERE l.ID = 14
)
I found an examples somewhere that says I need to have something like this:
var criteria = session.CreateCriteria(typeof(User));
var resellerSites = new[] { new ResellerSite { Id = 1 }, new ResellerSite { Id = 2 } };
criteria.Add(new InExpression("ResellerSite", resellerSites));
This is what I have so far:
var resellerSites = session.CreateCriteria<ResellerSite>("p")
.CreateCriteria("p.Locations", JoinType.InnerJoin)
.Add(Restrictions.Eq("locationID", locationId))
.List<ResellerSite>();
criteria.Add(new InExpression("ResellerSite", resellerSites));
var finalList = criteria.List<ResellerSite>();
The "criteria.Add(new InExpression" part is giving me an intellisense error, as InExpression seems to expect something like:
new[] { new ResellerSite { Id = 1 }, new ResellerSite { Id = 2 } };
Like in the first example.
Should I do a for loop like:
foreach (var site in resellerSites)
{
//somehow push into a new[] ?
}
or something like that or is there a better way?
Perhaps this entire approach is wrong?
I'd say that the typing problem comes from the double CreateCriteria and the single ToList()
Difficult to say without the table definitions, but, rereading you code, I wonder why you need the inner join with the locations.
May be you can rewrite your query as :
SELECT DISTINCT
U.ID as CID
FROM User U
INNER JOIN ResellerSites rs
on U.ID = rs.RID
and rs.LID=14
And have your code like (not tested and not optimal as you could have only one criteria query with join)
var resellerSites = session.CreateCriteria<ResellerSite>()
.Add(Expression.Eq("locationID", locationId))
.List<ResellerSite>();
criteria.Add(new InExpression("ResellerSite", resellerSites.ToArray()));
var finalList = criteria.List<ResellerSite>();
You can easily convert resellerSites to array using Linq:
criteria.Add(new InExpression("ResellerSite", resellerSites.ToArray()));
Also this question may help: Cannot use collections with InExpression

Help troubleshooting LINQ query

I have this LINQ query:
var returnList = from TblItemEntity item in itemList
join TblClientEntity client in clientList
on item.ClientNo equals client.ClientNumber
join TblJobEntity job in jobList
on item.JobNo equals job.JobNo
where item.ClientNo == txtSearchBox.Text //Is this filter wrong?
orderby client.CompanyName
select new { FileId = item.FileId, CompanyName = client.CompanyName, LoanStatus = item.LoanStatus, JobNo = job.JobNo, JobFinancialYE = job.JobFinancialYE, VolumeNo = item.VolumeNo };
Why doesn't this return anything?
P/S : All of them are of string datatype.
Have you tried to remove parts of the join to figure out where the problem is and then add those removed parts back again one after one? Start with:
var returnList = from TblItemEntity item in itemList
where item.ClientNo == txtSearchBox.Text //Is this filter wrong?
select new { FileId = item.FileId };
Since you're doing inner joins there could be that one of the joins filters out all the items.
EDIT: When debugging don't expand the return type, the select new {FileId = item.FileId} is all you need to debug.
Still waiting on that sample data.
You say you're getting results filtering by other attributes so why should this be any different? Assuming the user-input txtSearchBox has a reasonable value, try printing the values out onto the debug console and see if you're getting reasonable results. Look at the output window. Try this version of your query:
Func<string,bool> equalsSearch = s =>
{
var res = s == txtSearchBox.Text;
Debug.WriteLine("\"{0}\" == \"{1}\" ({2})", s, txtSearchBox.Text, res);
return res;
};
var returnList = from TblItemEntity item in itemList
join TblClientEntity client in clientList
on item.ClientNo equals client.ClientNumber
join TblJobEntity job in jobList
on item.JobNo equals job.JobNo
//where item.ClientNo == txtSearchBox.Text //Is this filter wrong?
where equalsSearch(item.ClientNo) //use our debug filter
orderby client.CompanyName
select new { FileId = item.FileId, CompanyName = client.CompanyName, LoanStatus = item.LoanStatus, JobNo = job.JobNo, JobFinancialYE = job.JobFinancialYE, VolumeNo = item.VolumeNo };
Why doesn't this return anything?
There two possibilites:
1) The join is empty, that is, no items, clients and jobs have matching ID's.
2) The where clause is false for all records in the join.
To troubleshoot this you will have to remove the where clause and/or some of the joined tables to see what it takes to get any results.

Problem with order by in LINQ

I'm passing from the controller an array generated by the next code:
public ActionResult GetClasses(bool ajax, string kingdom)
{
int _kingdom = _taxon.getKingdom(kingdom);
var query = (from c in vwAnimalsTaxon.All()
orderby c.ClaName
select new { taxRecID = c.ClaRecID, taxName = c.ClaName }).Distinct();
return Json(query, JsonRequestBehavior.AllowGet);
}
The query List should be ordered, but it doesn't work, I get the names of the classes ordered wrong in the array, because I've seen it debugging that the names are not ordered.The view is just a dropdownbox loaded automatically, so I'm almost sure the problem is with the action. Do you see anything wrong?Am I missing something?
I think gmcalab is almost there. The reason it's not working is that Distinct blows away the ordering. So you need Distinct THEN OrderBy. But this means you have to sort by the new attribute name:
var query = (from c in vwAnimalsTaxon.All()
select new { taxRecID = c.ClaRecID, taxName = c.ClaName }
).Distinct().OrderBy(t => t.taxName);
Give this a try:
var query = (from c in vwAnimalsTaxon.All()
select new { taxRecID = c.ClaRecID, taxName = c.ClaName }
).Distinct().OrdeyBy(c => c.ClaName);
In LINQ the Distinct method makes no guarantees about the order of results. In many cases the Distinct causes the OrderBy method to get optimized away. So it's necessary to do the OrderBy last, after the Distinct.
var query = (from c in vwAnimalsTaxon.All()
select new { taxRecID = c.ClaRecID, taxName = c.ClaName })
.Distinct()
.OrderBy(c => c.ClaName);
The select will also blow away the sorting. So either Distinct or Select needs orderby after.

Categories