Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing the ODATA $expand query option with WebAPI and a ViewModel
    text
    copied!<p><a href="https://stackoverflow.com/questions/19323545/odata-expand-dtos-and-entity-framework">This question</a> is very similar but does not give me what I need.</p> <p>I am using Entity Framework 6. My database has two tables, Customers and CustomerTypes. I have created a ViewModel for each. A customer can have a type:</p> <pre><code>public class Customer { public int CustomerID { get; set; } public string CustomerName { get; set; } public CustomerTypeViewModel CustomerType { get; set; } } public class CustomerTypeViewModel { public int CustomerTypeID { get; set; } public string CustomerTypeDescription { get; set; } } </code></pre> <p>I have a Customer controller which exposes an odata action method with a return type of IQueryable:</p> <pre><code>[HttpPost, Queryable(AllowedQueryOptions = AllowedQueryOptions.All)] public IQueryable&lt;CustomerViewModel&gt; GetCustomersMatchingCriteria([FromBody]ODataActionParameters parameters) { var criteria = (CustomerMassUpdateCriteriaViewModel)parameters["Criteria"]; return Common.Customers.GetCustomerMassUpdateCriteriaResults(criteria, ConfigurationManager.AppSettings["CLIENT_ID"]).Select( c =&gt; new CustomerViewModel() { CustomerID = c.CustomerID, CustomerName = c.CustomerName, CustomerType = new CustomerTypeViewModel() { CustomerTypeDescription = c.CustomerType.CustomerTypeDescription } }); } </code></pre> <p>The Common.Customers.GetCustomerMassUpdateCriteriaResults method just returns an IQueryable of Customer, which is the actual entity.</p> <p>The problem is, when calling this controller method with the following query string options:</p> <pre><code>$expand=CustomerType $select=CustomerID,CustomerName,CustomerType/CustomerTypeDescription </code></pre> <p>This exception is thrown:</p> <p><em>The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","type":"System.InvalidOperationException"</em></p> <p><em>The argument to DbIsNullExpression must refer to a primitive, enumeration or reference type.</em></p> <p>Removing the $expand option and the associated CustomerType/CustomerTypeDescription property from the $select list produces no error.</p> <p>I feel like I'm missing something obvious, here. Any ideas?</p> <p><strong>1st EDIT:</strong></p> <p>Enumerating the results via the ToList() extension method and returning IEnumerable rather than IQueryable successfully expands the CustomerType navigation property, but my ODATA $select list is no longer respected at the database level. Doesn't that defeat the purpose of using ODATA?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload