Monday, July 29, 2013

Eager Loading in Linq To Sql : Two ways

Two ways for Eager Loading in Linq to SQL
The first option is the DataLoadOptions, and the second is to utilize a ViewModel class.


DataLoadOptions
The first one is easy and simple to code, but not very good if you want to write back data to the database.

[HttpGet]
public ActionResult WebsiteImages()
{
    Web.WebDB db = new Web.WebDB();
    DataLoadOptions options = new DataLoadOptions();
    options.LoadWith<Web.Model.WebsiteImage>(x => x.Website);
    options.LoadWith<Web.Model.WebsiteImage>(c => c.WebsiteLanguage);
    db.LoadOptions = options;
  
    IEnumerable<Web.Model.WebsiteImage> websiteImages = db.WebsiteImages;
    return View(websiteImages);
}




ViewModel Class
The second option is a little bit more work, but you can easily persist data to the database on post backs. This option requires you to create a custom class to hold the reference data.

[HttpGet]
public ActionResult WebsiteImages()
{
    Web.WebDB db = new Web.WebDB();
    WebViewModel webVM = new WebViewModel();
    webVM.WebsiteImagesLinking = (from wi in db.WebsiteImages
                         select new WebsiteImagesVM
                         {
                             ID = wi.ID,
                             WebsiteImage = wi.WebsiteImage1,
                             Website = wi.Website,
                             WebsiteID = wi.WebsiteID,
                             WebsiteLanguage = wi.WebsiteLanguage,
                             Image = wi.Image,
                             ImageID = wi.ImageID,
                             MinWidth = wi.MinWidth,
                             MinHeight = wi.MinHeight,
                             MaxWidth = wi.MaxWidth,
                             MaxHeight = wi.MaxHeight,
                             Notes = wi.Notes
                         }).ToList();
      return View(webVM);
}


public List<WebsiteImagesVM> WebsiteImagesLinking { getset; }


public class WebsiteImagesVM
    {
        public int ID { getset; }
        public string WebsiteImage { getset; }
        public int WebsiteID { getset; }
        public Web.Model.Website Website { getset; }
        public Web.Model.WebsiteLanguage WebsiteLanguage { getset; }
        public int? ImageID { getset; }
        public Web.Model.Image Image { getset; }
        public int? MinWidth { getset; }
        public int? MinHeight { getset; }
        public int? MaxWidth { getset; }
        public int? MaxHeight { getset; }
        public string Notes { getset; }
        public bool Mapped { getset; }
    }