I have a ViewModel called EntityRating, one of whose properties is AverageRating.
When I instantiate a new object of my ViewModel (called EntityRating) type, how do I set the EntityRating.AverageRating based on the Rating field (in SQL Server) of the item in question?
I want to do something like this (which obviously doesn’t work):
var er = new EntityRating()
{
AverageRating = _db.All<Ratings>(X => X.RatingID = rating.RatingID).Average(RatingField);
};
Can I average the properties of an object in the database and assign it to the property of an object in my code?
(Pretty new, so let me know if any terminology is off, or if you need more info)
Thanks.
LINQ has the
.Averageextension method, however, that only works on integers. So what you need to do is get anIEnumerableof theRatingFieldproperty on all yourRatingobjects in the database. This can be accomplished by using the.Selectextension method of LINQ whichProjects each element of a sequence into a new form.