title: OData $expand, DTOs, and Entity Framework
body: <p>I have a basic WebApi service setup with a database first EF DataModel set up. I am running the nightly builds of WebApi, EF6, and the WebApi OData packages. (WebApi: 5.1.0-alpha1, EF: 6.1.0-alpha1, WebApi OData: 5.1.0-alpha1)</p>
  
  <p>The database has two tables: Product and Supplier. A Product can have one Supplier. A Supplier can have multiple Products.</p>
  
  <p>I have also created two DTO classes:</p>
  
  <pre><code>public class Supplier
  {
      [Key]
      public int Id { get; set; }
  
      public string Name { get; set; }
  
      public virtual IQueryable&lt;Product&gt; Products { get; set; }
  }
  
  public class Product
  {
      [Key]
      public int Id { get; set; }
  
      public string Name { get; set; }
  }
  </code></pre>
  
  <p>I have set up my WebApiConfig as follows:</p>
  
  <pre><code>public static void Register(HttpConfiguration config)
  {
      ODataConventionModelBuilder oDataModelBuilder = new ODataConventionModelBuilder();
  
      oDataModelBuilder.EntitySet&lt;Product&gt;("product");
      oDataModelBuilder.EntitySet&lt;Supplier&gt;("supplier");
  
      config.Routes.MapODataRoute(routeName: "oData",
          routePrefix: "odata",
          model: oDataModelBuilder.GetEdmModel());
  }
  </code></pre>
  
  <p>I have set up my two controllers as follows:</p>
  
  <pre><code>public class ProductController : ODataController
  {
      [HttpGet]
      [Queryable]
      public IQueryable&lt;Product&gt; Get()
      {
          var context = new ExampleContext();
  
          var results = context.EF_Products
              .Select(x =&gt; new Product() { Id = x.ProductId, Name = x.ProductName});
  
          return results as IQueryable&lt;Product&gt;;
      }
  }
  
  public class SupplierController : ODataController
  {
      [HttpGet]
      [Queryable]
      public IQueryable&lt;Supplier&gt; Get()
      {
          var context = new ExampleContext();
  
          var results = context.EF_Suppliers
              .Select(x =&gt; new Supplier() { Id = x.SupplierId, Name = x.SupplierName });
  
          return results as IQueryable&lt;Supplier&gt;;
      }
  }
  </code></pre>
  
  <p>Here is the metadata that gets returned. As you can see, the navigation properties are set up correctly:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx"&gt;
   &lt;edmx:DataServices m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"&gt;
    &lt;Schema Namespace="StackOverflowExample.Models" xmlns="http://schemas.microsoft.com/ado/2009/11/edm"&gt;
     &lt;EntityType Name="Product"&gt;
      &lt;Key&gt;
       &lt;PropertyRef Name="Id" /&gt;
      &lt;/Key&gt;
      &lt;Property Name="Id" Type="Edm.Int32" Nullable="false" /&gt;
      &lt;Property Name="Name" Type="Edm.String" /&gt;
     &lt;/EntityType&gt;
     &lt;EntityType Name="Supplier"&gt;
      &lt;Key&gt;
       &lt;PropertyRef Name="Id" /&gt;
      &lt;/Key&gt;
      &lt;Property Name="Id" Type="Edm.Int32" Nullable="false" /&gt;
      &lt;Property Name="Name" Type="Edm.String" /&gt;
      &lt;NavigationProperty Name="Products" Relationship="StackOverflowExample.Models.StackOverflowExample_Models_Supplier_Products_StackOverflowExample_Models_Product_ProductsPartner" ToRole="Products" FromRole="ProductsPartner" /&gt;
     &lt;/EntityType&gt;
     &lt;Association Name="StackOverflowExample_Models_Supplier_Products_StackOverflowExample_Models_Product_ProductsPartner"&gt;
      &lt;End Type="StackOverflowExample.Models.Product" Role="Products" Multiplicity="*" /&gt;
      &lt;End Type="StackOverflowExample.Models.Supplier" Role="ProductsPartner" Multiplicity="0..1" /&gt;
     &lt;/Association&gt;
    &lt;/Schema&gt;
    &lt;Schema Namespace="Default" xmlns="http://schemas.microsoft.com/ado/2009/11/edm"&gt;
     &lt;EntityContainer Name="Container" m:IsDefaultEntityContainer="true"&gt;
      &lt;EntitySet Name="product" EntityType="StackOverflowExample.Models.Product" /&gt;
      &lt;EntitySet Name="supplier" EntityType="StackOverflowExample.Models.Supplier" /&gt;
       &lt;AssociationSet Name="StackOverflowExample_Models_Supplier_Products_StackOverflowExample_Models_Product_ProductsPartnerSet" Association="StackOverflowExample.Models.StackOverflowExample_Models_Supplier_Products_StackOverflowExample_Models_Product_ProductsPartner"&gt;
        &lt;End Role="ProductsPartner" EntitySet="supplier" /&gt;
        &lt;End Role="Products" EntitySet="product" /&gt;
       &lt;/AssociationSet&gt;
      &lt;/EntityContainer&gt;
     &lt;/Schema&gt;
    &lt;/edmx:DataServices&gt;
  &lt;/edmx:Edmx&gt;
  </code></pre>
  
  <p>So the normal array of odata queries work fine: /odata/product?$filter=Name+eq+'Product1' and /odata/supplier?$select=Id for example all work fine.</p>
  
  <p>The problem is when I attempt to work with $expand. If I were to do /odata/supplier?$expand=Products, I of course get an error:</p>
  
  <blockquote>
    <p>"The specified type member 'Products' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."</p>
  </blockquote>
  
  <p><strong>Update:</strong>
  I keep getting the same questions so I am adding more information. Yes, the navigation properties are set up correctly as can be seen in the metadata information I posted above.</p>
  
  <p>This is not related to methods being missing on the controller. If I were to create a class that implements IODataRoutingConvention, /odata/supplier(1)/product would be parsed out as "~/entityset/key/navigation" just fine.</p>
  
  <p>If I were to bypass my DTOs completely and just return the EF generated classes, $expand works out of the box. </p>
  
  <p><strong>Update 2:</strong>
  If I change my Product class to the following:</p>
  
  <pre><code>public class Product
  {
      [Key]
      public int Id { get; set; }
  
      public string Name { get; set; }
  
      public virtual Supplier Supplier { get; set; }
  }
  </code></pre>
  
  <p>and then change the ProductController to this:</p>
  
  <pre><code>public class ProductController : ODataController
  {
      [HttpGet]
      [Queryable]
      public IQueryable&lt;Product&gt; Get()
      {
          var context = new ExampleContext();
  
          return context.EF_Products
              .Select(x =&gt; new Product() 
              { 
                  Id = x.ProductId, 
                  Name = x.ProductName, 
                  Supplier = new Supplier() 
                  {
                      Id = x.EF_Supplier.SupplierId, 
                      Name = x.EF_Supplier.SupplierName 
                  } 
              });
      }
  }
  </code></pre>
  
  <p>If I were to call /odata/product I would get back what I expected. An array of Products with the Supplier field not returned in the response. The sql query generated joins and selects from the Suppliers table, which would make sense to me if not for the next query results.</p>
  
  <p>If I were to call /odata/product?$select=Id, I would get back what I would expect. But $select translates to a sql query that does not join to the suppliers table.</p>
  
  <p>/odata/product?$expand=Product fails with a different error:</p>
  
  <blockquote>
    <p>"The argument to DbIsNullExpression must refer to a primitive, enumeration or reference type."</p>
  </blockquote>
  
  <p>If I change my Product Controller to the following:</p>
  
  <pre><code>public class ProductController : ODataController
  {
      [HttpGet]
      [Queryable]
      public IQueryable&lt;Product&gt; Get()
      {
          var context = new ExampleContext();
  
          return context.EF_Products
              .Select(x =&gt; new Product() 
              { 
                  Id = x.ProductId, 
                  Name = x.ProductName, 
                  Supplier = new Supplier() 
                  {
                      Id = x.EF_Supplier.SupplierId, 
                      Name = x.EF_Supplier.SupplierName 
                  } 
              })
              .ToList()
              .AsQueryable();
      }
  }
  </code></pre>
  
  <p>/odata/product, /odata/product?$select=Id, and /odata/product?$expand=Supplier return the correct results, but obviously the .ToList() defeats the purpose a bit.</p>
  
  <p>I can try to modify the Product Controller to only call .ToList() when an $expand query is passed, like so:</p>
  
  <pre><code>    [HttpGet]
      public IQueryable&lt;Product&gt; Get(ODataQueryOptions queryOptions)
      {
          var context = new ExampleContext();
  
          if (queryOptions.SelectExpand == null)
          {
              var results = context.EF_Products
                  .Select(x =&gt; new Product()
                  {
                      Id = x.ProductId,
                      Name = x.ProductName,
                      Supplier = new Supplier()
                      {
                          Id = x.EF_Supplier.SupplierId,
                          Name = x.EF_Supplier.SupplierName
                      }
                  });
  
              IQueryable returnValue = queryOptions.ApplyTo(results);
  
              return returnValue as IQueryable&lt;Product&gt;;
          }
          else
          {
              var results = context.EF_Products
                  .Select(x =&gt; new Product()
                  {
                      Id = x.ProductId,
                      Name = x.ProductName,
                      Supplier = new Supplier()
                      {
                          Id = x.EF_Supplier.SupplierId,
                          Name = x.EF_Supplier.SupplierName
                      }
                  })
                  .ToList()
                  .AsQueryable();
  
              IQueryable returnValue = queryOptions.ApplyTo(results);
  
              return returnValue as IQueryable&lt;Product&gt;;
          }
      }
  }
  </code></pre>
  
  <p>Unfortunately, when I call /odata/product?$select=Id or /odata/product?$expand=Supplier it throws a serialization error because returnValue can't be cast to IQueryable. I can be cast though if I call /odata/product.</p>
  
  <p>What is the work around here? Do I just have to skip trying to use my own DTOs or can/should I roll my own implementation of $expand and $select?</p>