Search code examples
entity-framework-coresumautomappericollection

Nullable object must have a value when deviding


I have the following mapping:

 .ForMember(dest => dest.AskerAverageRating, opt => opt.MapFrom(src =>
      src.ReviewsReceived != null?
      ((float)src.ReviewsReceived.Sum(r => r.Rating) / (float)src.ReviewsReceived.Count()) : 0))  

This alone:

(float)src.ReviewsReceived.Sum(r => r.Rating)  

Works.

This alone:

(float)src.ReviewsReceived.Count()  

Also works.

Devided however, they give the following error:

 System.InvalidOperationException: Nullable object must have a value.  

Why???

Here are the relevant Properties and entities:

This is the destination

public float AskerAverageRating { get; set; }  

These is the source:

public ICollection<Review> ReviewsReceived { get; set; }  

This is Review:

public class Review
{
    ..
    public int Rating { get; set; }
    ..  

..And I found nothing funky in the DB.


Solution

  • You are missing parentheses around src.ReviewsReceived != null.

    Please find working solution here: https://dotnetfiddle.net/gaGZp0