Using linq to return an object with a list<object> member
I am still somewhat new to Linq to SQL. I am looking for a way to get all members of an object by using a single linq query. The problem I haev run into is that one of the class members is a list of custom objects. It goes something like this:
Class:
public class RoomConfiguration
{
public int ConfigID {get;set;}
public string ConfigName { get; set; }
public int RowCount { g开发者_如何学Cet; set; }
public int ColCount { get; set; }
public int FillDirection { get; set; }
public string BigDoor { get; set; }
public string SmallDoor { get; set; }
public List<LineConfig> Lines { get; set; }
}
I am looking for a linq query that will fill in all of the members of this class, including Lines. The data for Lines comes from another table which I have defined a class for as well.
Thank you to anyone who may have a solution for this. Help is much appreciated!
It's a little hard, not knowing how your tables relate, but you could do this:
var configs = db.RoomConfigurations
.Select( r => new RoomConfiguration
{
ConfigID = r.ConfigID,
ConfigName = r.ConfigName,
...
Lines = db.LineConfigs
.Where( l => l.RoomConfigID == r.ConfigID )
.ToList()
});
Or
var configs = db.RoomConfigurations
.Join( db.LineConfigs, r => r.ConfigID, l => l.RoomConfigID, (r,l) => new { RoomConfig = r, LineConfigs = l } )
.GroupBy( j => j.RoomConfig )
.Select( g => new RoomConfiguration
{
ConfigID = g.Key.ConfigID,
ConfigName = g.Key.ConfigName,
...
Lines = g.LineConfigs.ToList()
});
精彩评论