1

I have the following controller method:

public IActionResult Get()
{
    IEnumerable<Hour> _hours = _hourRepository
        .AllIncluding(h => h.Customer.name, h => h.Payer.name)
        .OrderByDescending(h => h.hourdate)
        .ToList();

    return Ok(_hours);
}

I want to change the method to use aliases because both Customer and Payer return the same name field.

public IActionResult Get()
{
    IEnumerable<Hour> _hours = _hourRepository
        .AllIncluding(
                 h => new { customer_name = h.Customer.name }, 
                 h => new { payer_name = h.Payer.name })
        .OrderByDescending(h => h.hourdate)
        .ToList();

     return Ok(_hours);
}

This however results in an error as I use a repository which does not support this ... I think.

The property expression 'h => new <>f__AnonymousType1`1(customer_name = h.Customer.name)' is not valid. The expression should represent a property access: 't => t.MyProperty'

Below my repository:

public virtual IEnumerable<T> AllIncluding(params Expression<Func<T, 
                                       object>>[] includeProperties)
{
    IQueryable<T> query = _context.Set<T>();
    foreach (var includeProperty in includeProperties)
    {
        query = query.Include(includeProperty);
    }
    return query.AsEnumerable();
}

How would I change the repository method AllIncluding to accept both options as described above?

Maksim Simkin
  • 9,100
  • 4
  • 34
  • 47
phicon
  • 3,024
  • 4
  • 25
  • 54
  • 2
    From what I see, even the first method can't work. You can't include an expression like `h => h.Customer.name`, only `h => h.Customer`. Next, you get an object graph in which each object has its own unique property names, there can't be any conflicts. – Gert Arnold Jan 07 '17 at 15:22
  • ah, that explains. I only want to return the names though, any ideas? – phicon Jan 07 '17 at 15:23
  • 1
    Then you should return a *projection*: `Select(h => new SomeDto { CustomerName = h.Customer.Name, PayerName = h.Payer.Name }`. – Gert Arnold Jan 07 '17 at 15:26
  • ty - will look into projections – phicon Jan 07 '17 at 15:26

0 Answers0