I seem confused by a pretty likely solution. I usually used lazy loading in EF 4.1, and now I'm trying to use loading in the application, so I can use the built-in JSON serializer without any problems. The problem is that I cannot figure out how to use .Include () to load multiple grandchildren relationships at the same level.
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 tried the following without success. How to write download code to download TextContents and ImageContents?
Not compiling:
var c = dataContext.Canvases .Include(ca => ca.Contents.Select(co => co.ImageContents).Select(co => co.TextContents)) .FirstOrDefault();
Doesn't work, second Turn on overrides first:
var c = dataContext.Canvases .Include(ca => ca.Contents.Select(co => co.ImageContents)) .Include(ca => ca.Contents.Select(co => co.TextContents)) .FirstOrDefault();
Does not work, throws an exception at runtime:
var c = dataContext.Canvases .Include(ca => ca.Contents.Select(co => new { co.ImageContents, co.TextContents })) .FirstOrDefault();
Edit:
I abandoned this approach at the moment and just made view models based on some other articles and approaches that they adopted, solving the problem of "serializing an entity" with ASP.NET MVC built into JSON serialization. This made me duplicate my classes, but with the AutoMapper library, it was easy to transfer all the data back and forth automatically.
source share