Reputation: 85
I'm using a Linq query to fill a gridview, the last column of the gv contains a partners average rating, which is my problem. When a person never has been rated, I'm expecting a null value, and I try to switch that to a 0 with a coalescing operator. But I'm getting a "System.InvalidCastException: Specified cast is not valid." that I cannot figure out why.
I've never used a subquery like this in linq before, so please correct me if I'm on the wrong path on that.
I'm using entity framework with my database
MembershipUser u = Membership.GetUser(User.Identity.Name);
using (DatabaseEntities db = new DatabaseEntities())
{
var q = from job in db.Jobs
join employer in db.UserProfiles on job.UserId equals employer.UserId
where job.ServiceProviderUid == (Guid)u.ProviderUserKey &&
job.Finished
select new
{
JobId = job.JobId,
Title = job.Title,
Partner = employer.FullName,
Rating = (from ur in db.User_Ratings
where ur.UserId == employer.UserId
select (int?)ur.Rating).Average() ?? 0
};
GridView1.DataSource = q.ToList();
GridView1.Columns[2].HeaderText = "Employer";
GridView1.DataBind();
}
Upvotes: 1
Views: 1605
Reputation: 10865
You want it like this
(int?)(from ur in db.User_Ratings
where ur.UserId == employer.UserId
select (int)ur.Rating).Average() ?? 0
You can't use null coalescing if it is not checking for null objects. Average returns an int and it can't do ?? against it. You tried putting the (int?) in the select that's fine if you want and then it does the average which might return again an int and not a nullable one.
Upvotes: 3
Reputation:
Try this:
select new
{
JobId = job.JobId,
Title = job.Title,
Partner = employer.FullName,
Rating = (from ur in db.User_Ratings
where ur.UserId == employer.UserId
select (int)ur.Rating).Average() ?? 0 // Remove the ? after int
};
Regarding your error.
Upvotes: 0