I have a few models that I fill in using entity framework with a MS SQL Server back end. The model consist of a record and many records that associate with that one record. I use a list to hold these records. In a LINQ Entity framework query, I write a sub query to get the list, but I don't know if I'm making a trip to the database at that moment. I may want to add on a where clause later etc.
This is the way I currently do it:
public class TestOwner
{
public Owner OwnerRecord { get; set; }
public List<OwnerUser> OwnerUsers { get; set; }
public TestOwner()
{
}
}
public static class DataTools
{
public static TestOwner testQuery()
{
//Create the holder variable for the database context.
MyEntities db = (MyEntities)CommonDataTools.GetDbContext();
//Places the database context in a using statement to have it disposed of when we are done.
using (db)
{
//Get the test owner.
return (from o in db.Owner
where o.owner_id == 44
select new TestOwner()
{
OwnerRecord = o,
OwnerUsers = (from ou in db.OwnerUser
where ou.owner_id == o.owner_id
select ou).ToList() //This is the part in question, what does this do in the database? Is this the proper way?
}).FirstOrDefault();
}
}
}
Note the query where I turn the sub query into a list.
I've been wondering if this is "better":
public class TestOwner
{
public Owner OwnerRecord { get; set; }
public IEnumerable<OwnerUser> OwnerUsers { get; set; }
public TestOwner()
{
}
}
By making in IEnumerable, I don't need the .ToList but I'm not sure if that will hurt me later on.
So for the list version, what does that do in the database? Does the query partially get run? Is this the proper way to handle this situation? If not, how is the correct way to fill a list inside of the object we are filling from the database?