简体   繁体   中英

Get 3 layered object using entity framework

If i have a manufacturer object that has a list of cars, and the car object has a list of features how do i return a manufacturer object that contains the list of all the cars and each car in that list contains a list of features. Every example i see online just uses a 2 layered object. This is what i have and it returns a manufacturer and list of cars, but each car returns 0 results for the list of features

        Manufacturer man = new Manufacturer();
        using (MyEntities db = new MyEntities())
        {
            man= (from m in db.Manufacturer.Include("Cars")
                    where m.Name.Trim().Equals("Ford")
                    select m).FirstOrDefault();
        }
        return man;

mayIf you want to use Lazy loading, just declare your navigation properties as 'Virtual'

If you want to eager load all the related objects, you can use Includes :

.Include("Cars").Include("Cars.Features")

one drawback of this method is that the query will may be expensive to execute. The reason is that multiple join will be used and the size of the resulting server answer may be pretty big.

You can load one level at the time with this strategy :

    Manufacturer man = new Manufacturer();
    using (MyEntities db = new MyEntities())
    {
        man= (from m in db.Manufacturer
                where m.Name.Trim().Equals("Ford")
                select m).FirstOrDefault();

        models = man.SelectMany(m => m.Cars);

        features = models.SelectMany(m => m.Features);

        man.Load();
        models.Load();
        features.Load();
    }
    return man;

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