Parameterless aggregate operator 'Max' is not supported over projections - linq

Trying to get the max value from Union Query through LINQ
var query = (from x in db.GHProgresses select new {A=x.PatentCounter})
.Union(from y in db.YUMasters select new { A=y.PatentCounter }).Max();
Below is the err
Parameterless aggregate operator 'Max' is not supported over
projections.

You've declared an anonymous type new {A=x.PatentCounter} which can't be maximized by default. Add a projection:
var query = (from x in db.GHProgresses
select new { A = x.PatentCounter })
.Union(from y in db.YUMasters
select new { A = y.PatentCounter })
.Max(item => item.A); // <- Max of A

Related

Linq LeftJoin Nullable object must have a value Error

When i use y in my select it has "Nullable object must have a value" error
var products = productQuery.
.GroupJoin(customerProductPrices,
p => p.Id,
pp => pp.ProductId,
(p, pp) => new { Product = p, CustomerProductPrice = pp })
.SelectMany(
x => x.CustomerProductPrice.DefaultIfEmpty(),
(x, y) => new ProductFilterResultModel
{
Id = x.Product.Id,
Price = y != null ? y.Price : 0
});
I don't know what is your GroupJoin purpose? I don't have entities, from the example I can rewrite:
var products = customerProductPrices.Select(pp => new ProductFilterResultModel
{
Id = pp.Product.Id,
Price = pp != null ? pp.Price : 0
})
I found the error,
Thats because of my ProductFilterResultModel model, some properties in this model was not nullable but the datas which fetch from database and related to these properties was null. I change my nullable properties required type to the nullable type.

IQueryable.Union/Concat in .net core 3

I want to add a dummy member to an IQueryable and came up with this solution:
IQueryable<Geography> geographies = _unitOfWork.GeographyRepository.GetAll(); //DbSet<Geography>
var dummyGeographies = new Geography[] { new Geography { Id = -1, Name = "All" } }.AsQueryable();
var combinedGeographies = geographies.Union(dummyGeographies);
var test = combinedGeographies.ToList(); //throws runtime exc
But it throws the following exception:
Processing of the LINQ expression 'DbSet
.Union(EnumerableQuery { Geography, })' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core.
How could I make it work?!
you can only union on data structure which are the same
IQueryable is only applicable if the query expression not been been expressed (ToList) before its run against db and you want the expression modifiable . aka nothing which which is not going to db as a query needs to be IQueryable (simple explanation better to research and understand this yourself)
List<Geography> geographies = _unitOfWork.GeographyRepository
.GetAll() //DbSet<Geography>
.Select(o => new Geography { Id = o.Id, Name = o.Name })
.ToList();
List<Geography> dummyGeographies = new List<Geography>() {
new Geography[] { new Geography { Id = -1, Name = "All" } }
};
var combinedGeographies = geographies.Union(dummyGeographies);
var test = combinedGeographies.ToList();
I was able to achieve it with the following code:
IQueryable<Geography> geographies = _unitOfWork.GeographyRepository.GetAll().Select(o => new Geography { Id = o.Id, Name = o.Name });
IQueryable<Geography> dummyGeographies = _unitOfWork.GeographyRepository.GetAll().Select(o => new Geography { Id = -1, Name = "All" });
var combinedGeographies = geographies.Union(dummyGeographies);

nullable object must have a value linq to sql query

I have the following linq query that is throwing an error if a budget doesn't have any categories. Am I doing something wrong? Can I just set sum to return 0 if there are no categories? I'm fairly new to linq to sql.
var r = from rec in DbContext.budgets
where rec.budgetID == updatedBudget.budgetID
select new
{
rec.budgetID,
rec.totalIncome,
totalSpent = rec.categories.Sum(a => a.amount)
};
return new JsonResult(r.FirstOrDefault(), JsonSettings);
you can try this.
var r = from rec in DbContext.budgets
where rec.budgetID == updatedBudget.budgetID
select new
{
rec.budgetID,
rec.totalIncome,
totalSpent = rec.categories != null ? rec.categories.Sum(a => a.amount) : 0
};
return new JsonResult(r.FirstOrDefault(), JsonSettings);

Integrating custom method into LINQ to Entities query

I have a custom method that performs some calculation on a set of data:
private int GetPercentages(int OriginalValue, int TotalValue)
{
var newValue = (int)Math.Round(((decimal)OriginalValue / (decimal)TotalValue) * 100);
return newValue;
}
I need to be able to run this method inside of a LINQ to Entities query:
var data = from SurveyResponseModel in db.SurveyResponseModels
group SurveyResponseModel by SurveyResponseModel.MemberId into resultCount
select new ResultsViewModel()
{
MemberId = resultCount.Key,
PatientFollowUpResult = db.SurveyResponseModels.Count(r => r.PatientFollowUp),
PatientFollowUpResultPct = GetPercentages(db.SurveyResponseModels.Count(r => r.PatientFollowUp),totalResponsesResult),
ChangeCodingPracticeResult = db.SurveyResponseModels.Count(r => r.ChangeCodingPractice),
};
I need to run this on about 20 more lines inside of the query so just sticking it inline doesn't seem like a great option. I understand that it needs to be converted into SQL syntax, but is there anything else like this that I can do?
You need to make a lambda expression that calculates the percentage like this:
Expression<Func<int, int, int>> calcPercentage =
(OriginalValue, TotalValue) => (int)Math.Round(((decimal)OriginalValue / (decimal)TotalValue) * 100);
And use it like this:
var data = from SurveyResponseModel in db.SurveyResponseModels.ToExpandable()
group SurveyResponseModel by SurveyResponseModel.MemberId into resultCount
select new ResultsViewModel()
{
MemberId = resultCount.Key,
PatientFollowUpResult = db.SurveyResponseModels.Count(r => r.PatientFollowUp),
PatientFollowUpResultPct = calcPercentage.Invoke(db.SurveyResponseModels.Count(r => r.PatientFollowUp), totalResponsesResult),
ChangeCodingPracticeResult = db.SurveyResponseModels.Count(r => r.ChangeCodingPractice),
};
More info about calling functions in LINQ queries here.

group by base on 2 element

equal this
select id,name, count(*) from table group by id, name
what is in linq???
In case of entity framework it is better to return computed projection directly from SQL:
var query = from x in context.YourEntities
group x by new { x.ID, x.Name } into y
select new
{
y.Key.ID,
y.Key.Name,
y.Count()
};
This will do Count in database and reduce amount of transferred data.
var groups = table.GroupBy(elt => new {ID = elt.ID, Name = elt.name});
foreach (var group in groups)
{
var ID = group.Key.ID;
var name = group.Key.Name;
var count = group.Count();
...
}

Resources