I am trying to populate an instance with LINQ containing an array of nested classes. I have managed to do this with the following LINQ. I have also included the classes that make up the instance in the select.
select new EditableWarrantBook {
Id = p1.id,
Comment = p1.EntryComment,
WarrantYear1 = new BookYear {
StatusYear = p2.StatusYear,
Status = p2.Status,
},
WarrantYear2 = new BookYear {
StatusYear = p3.StatusYear,
Status = p3.Status,
},
WarrantYear3 = new BookYear {
StatusYear = p4.StatusYear,
Status = p4.Status,
}
}
public class EditableWarrantBook
{
public int Id { get; set; }
public string Comment { get; set; }
public BookYear[] WarrantYear = new BookYear[3];
public BookYear WarrantYear1
{
get { return WarrantYear[0]; }
set { WarrantYear[0] = value; }
}
public BookYear WarrantYear2
{
get { return WarrantYear[1]; }
set { WarrantYear[1] = value; }
}
public BookYear WarrantYear3
{
get { return WarrantYear[2]; }
set { WarrantYear[2] = value; }
}
}
public class BookYear
{
public int? StatusYear { get; set; }
public string Status { get; set; }
}
This works I can access values with either WarrantYear[0] or WarrantYear1. This can sometimes be useful when designing UI. However, in this case, I don’t need the WarrantYear1 property because I am turning this into JSON and I don’t need to repeat (or want to send two versions of the same data on the network). My question is, how do I write the select statement to load WarrantYear array. Or how do I write the class so that I can access the array as a property. My solution should not contain the Warrant1, Warrant2, Warrant3 properties in the EditableWarrantBook Class.
The problem is that you’re trying to mix SQL world (building your query) with your CLR world (creating new objects). The way to get around this is to break up your queries into your initial data fetching query (SQL world), and then enumerate over the results to transform into your objects (CLR world):
So after the
where p1.SaleYear == 2009, add this:If you want to stay in query syntax, then just change it to:
Edit: So I’ve modified the example one more time. It looks like one of the values that you’re getting back is null, so I’ve added a null check to make sure you’re not accessing properties of null objects (although I didn’t check
p1for null).