简体   繁体   中英

How to use Entity Framework's Navigation Properties to build a View Model

I'm having trouble finding the right mapping schema for my EF-based models.

我的业务对象

I have a given serial (device) and I want to create a view model containing all the relevant images with their respective categories. I only recently added the categories and that's where my problems started. Up until then I simply selected the relevant device with

dbCon.Devices.SingleOrDefault(d => d.serial == serial)

and then, using Automapper mapped its Images attribute to a List of images in the view model. Now I basically want to create a list with all involved categories, with respective collections of their related images. However I can't figure out how to start. What do I use instead of my initial device? I only want to receive categories with images that are related to the defined device.

I think I could figure out how to do it in a loop (loop over all the images and add their respective categories to a list), but then I think it wouldn't only link to images related to the device, but to all images related to the category. Also my impression was that with ORM I don't need loops up until the point where I process the data.

I have a given serial (device) and I want to create a view model containing all the relevant images with their respective categories.

Use navigation properties:

// Get Device
Device device = dbCon.Devices.SingleOrDefault(d => d.serial == serial);

// Get Device's Images
IQueryable<Image> images = device.Images;

// Get Images Categories
IQueryable<Category> categories = images.Select(c => c.Category);

Your View Model would look something like:

class DeviceImageCategoriesViewModel
{
    Device Device { get; set; }
    List<Category> Categories { get; set; }
}

var viewModel = new DeviceImageCategoriesViewModel
{
    Device = device,
    Categories = categories.ToList() // Each Category will have its navigation property back to Images
};

Or by using eager loading:

Device device = dbCon.Devices.SingleOrDefault(d => d.serial == serial) 
                             .Include(i => i.Images.Select(c => c.Categories)) 
                             .ToList(); 

List<Category> categories = device.Images.Select(c => c.Categories);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM