Database Reference
In-Depth Information
The corresponding POCO classes are shown in Listing 13-27. Note how each property includes the virtual
keyword and each reference to the Tracks property is of type ICollection . This will allow Entity Framework to create
the tracking proxies dynamically. (See Recipe 13-5 for more information on tracking proxy objects.)
Listing 13-27. The POCO Classes Along with Our Object Context
public partial class CD
{
public CD()
{
this.Tracks = new HashSet<Track>();
}
public int CDId { get; set; }
public string Title { get; set; }
public virtual ICollection<Track> Tracks { get; set; }
}
public partial class Track
{
public string Title { get; set; }
public string Artist { get; set; }
public int CDId { get; set; }
}
To cause Entity Framework to generate the proxies before they are required (before an entity is loaded), we need
to use the CreateProxyTypes() method on the object context, as illustrated in Listing 13-28.
Listing 13-28. Generating the tracking proxies before loading the entities
using (var context = new EFRecipesEntities())
{
// to trigger proxy generation we need to drop-down into the underlying
// ObjectContext object as DbContext does not expose the CreateProxyTypes() method
var objectContext = ((IObjectContextAdapter) context).ObjectContext;
objectContext.CreateProxyTypes(new Type[] { typeof(CD), typeof(Track) });
var proxyTypes = ObjectContext.GetKnownProxyTypes();
Console.WriteLine("{0} proxies generated!", ObjectContext.GetKnownProxyTypes().Count());
var cds = context.CDs.Include("Tracks");
foreach (var cd in cds)
{
Console.WriteLine("Album: {0}", cd.Title);
foreach (var track in cd.Tracks)
{
Console.WriteLine("\t{0} by {1}", track.Title, track.Artist);
}
}
}
 
Search WWH ::




Custom Search