Search code examples
asp.net-mvcentity-frameworklinq-to-entities

navigation property on a view


I got following situation. I have Deliverers and Promotions tables linked with DelivererId on Promotions (foreign key). In my MVC app I simply display list of promotions with this code:

                    promotions = db.Promotions.
                    Include("Deliverers1").
                    Where(p => p.WeekNo == currentWeek).
                    OrderByDescending(p => p.WeekNo);

I was asked to add another column which is dynamically computed (select count(*) on another table). My solution was to create a view as select *, count(....) from Promotions ....

The problem is that my view does not have Deliverers1 navigation property and I have no idea how to add it. Any suggestions?


Solution

  • If another table is a property navigation of this entity:

    var promotions = db.Promotions.
                        Include("Deliverers1").
                        Where(p => p.WeekNo == currentWeek).
                        OrderByDescending(p => p.WeekNo)
                        .Select(p=>new {p,p.Count(...));
    

    If not a property navigation:

    var promotions = db.Promotions.
                        Include("Deliverers1").
                        Where(p => p.WeekNo == currentWeek).
                        OrderByDescending(p => p.WeekNo)
                        .Select(p=>new {p,db.othertable.Where(q=>q.foo==p.foo).Count());