views:

376

answers:

3

I am getting "The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type" When executing Sum() of my empty statement. ResultView works fine, but either

var r = from v in DataContext.Visits
        join bs in DataContext.BaseContents on v.BaseContentID equals bs.Id
        where (bs.CreatedBy == userId) && (v.DateVisited.Year == workDate.Year) &&
        (v.DateVisited.Month == workDate.Month) && (v.DateVisited.Day == workDate.Day) &&
        (v.IsPreviewed == false) && (bs.ProfileProjectId != null)
        select v;

int? number = r.Sum( v => v.Counter);

either

var r = from v in DataContext.Visits
        join bs in DataContext.BaseContents on v.BaseContentID equals bs.Id
        where (bs.CreatedBy == userId) && (v.DateVisited.Year == workDate.Year) &&
        (v.DateVisited.Month == workDate.Month) && (v.DateVisited.Day == workDate.Day) &&
        (v.IsPreviewed == false) && (bs.ProfileProjectId != null)
        select v.Counter;

int? number = r.Sum(v);

fails with same exception.

+4  A: 

Try this (updated):

int number = r.Sum(v => (int?)v.Counter) ?? 0;
bruno conde
I tryied already, compile time error:Operator '??' cannot be applied to operands of type 'int' and 'int'
Sergey Osypchuk
See my updated answer.
bruno conde
A: 

Seems like putting && (v.Counter != null) would filter out all nulls for that value before running the sum.

L. Moser
In database and linq Counter is not nullable :(
Sergey Osypchuk
I'd go back and try to figure out why you're getting any nulls at all. If the types are non-null and you're using the LINQ join (which is the same as sql INNER JOIN) then you should not be getting nulls. Something doesn't add up. (Probably why you're asking the question).
L. Moser
A: 

Could you include some sample data? At the very least you might grab r.ToList() and look at the values by hand. From what I can see this looks like it should work fine. Also make sure that v.BaseContentID, bs.Id and v.DateVisited are not nullable. (especially the ID columns) Any nullable integers that are referenced could cause that exception. Not just the ones in the Select clause

var r = from v in DataContext.Visits
        join bs in DataContext.BaseContents on v.BaseContentID equals bs.Id
        where (bs.CreatedBy == userId) 
            && (v.DateVisited.Date == workDate.Date)
            && (!v.IsPreviewed) 
            && (bs.ProfileProjectId.HasValue)
        select v;

int? number = r.Sum(v => v.Counter);
Matthew Whited