0
votes

I have a table and need to get list by grouping Field1 and Field2

public class Journal
{
    public int ID {get; set;}
    public string DateField { get; set; }
    public string Notes { get; set; }
    public int Field1 { get; set; }
    public string Field2 { get; set; }
}

First of all I filter data by Field2 (string) and when grouping by two fields (Field1 and Field2)

MyList = DBContext.Journals.Where(f=>f.Field2.StartsWith(someParam))
                           .GroupBy(g => new { g.Field1, g.Field2 })
                           .Select(n=> n.Key.Field1).ToList();

If Field1 and Field2 is not null, everything is ok, but how to solve a problem if they are null, could You help?

If there are nulls, I got an exception:

"The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."

1
Field1 can't ever be null -- it's a value type.Rob Lyndon
Use public int? Field1 { get; set; } in Journal ;).shA.t
And what about MyList? List<int> MyList = new List<int>(); ?Songaila
@Songaila Did you try doing a null check ? Something like: DBContext.Journals.Where(f => ! (f.Field2 == null || f.Field2.Equals(string.Empty) ) && f.Field2.StartsWith(someParam))Siva Gopal
A bigest problem for me is about that int type field... with string is okSongaila

1 Answers

1
votes

have you tried maybe with something like:

MyList = DBContext.Journals.Where(f=> !String.IsNullOrEmpty(f.Field1) && f.Field2 != null && (f.Field2.StartsWith(someParam)))
                           .GroupBy(g => new { g.Field1, g.Field2 })
                           .Select(n=> n.Key.Field1).ToList();