Reputation: 248
I'm seemingly stumped by a likely simple solution. I've typically used lazy loading in EF 4.1, and I'm now trying to use eager loading in my application so I can use the built-in JSON serializer without issues. The problem I am having is that I can't figure out how to use .Include() to load multiple same-level grandchild relationships.
public class Canvas
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<ContentArea> Contents { get; set; }
}
public class ContentArea
{
public int ID { get; set; }
public int CanvasID { get; set; }
public string Name { get; set; }
public ICollection<TextContent> TextContents { get; set; }
public ICollection<ImageContent> ImageContents { get; set; }
}
public class TextContent
{
public int ID { get; set; }
public int ContentAreaID { get; set; }
public string Text { get; set; }
public int Color { get; set; }
}
public class ImageContent
{
public int ID { get; set; }
public int ContentAreaID { get; set; }
public string Filename { get; set; }
}
I've tried the following with no success. How can I write the loading code to load TextContents and ImageContents?
Doesn't compile:
var c = dataContext.Canvases
.Include(ca => ca.Contents.Select(co => co.ImageContents).Select(co => co.TextContents))
.FirstOrDefault();
Doesn't work, second Include overrides first:
var c = dataContext.Canvases
.Include(ca => ca.Contents.Select(co => co.ImageContents))
.Include(ca => ca.Contents.Select(co => co.TextContents))
.FirstOrDefault();
Doesn't work, throws runtime exception:
var c = dataContext.Canvases
.Include(ca => ca.Contents.Select(co => new { co.ImageContents, co.TextContents }))
.FirstOrDefault();
Edit:
I've given up on this approach for now and just made view models based on some other articles and approaches they have taken solving the "serializing Entity models" problem with the ASP.NET MVC built in JSON serialization. This caused me to duplicate my classes, but it was made easy by using the AutoMapper library to transfer all of the data back and forth automatically.
Upvotes: 4
Views: 1710
Reputation: 4108
I have succeeded with following codes
var contents = db.Canvases
.Include(c=>c.Contents.Select(co=>co.TextContents))
.Include(c=>c.Contents.Select(co=>co.ImageContents))
.ToList();
Upvotes: 3