2016-09-27 81 views
1

我有一个OData服务使用WebAPI和EF 6构建。我使用流畅的api来创建我的模型。它工作正常,但是当我使用$expand时,它省略了扩展属性为null的实体。

这是一个简化的例子:

public class Customer 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public int? AddressId { get set; } // Note that Address is optional 
    public Address Address { get; set; } 
} 

public class Address 
{ 
    public int Id { get; set; } 
    public string Street{ get; set; } 
} 


public class CustomersController : ODataController 
{ 
    [EnableQuery] 
    public virtual IQueryable<Customer> Get(ODataQueryOptions<Customer> q) 
    { 
     // I return IQueryable from DBSet here... 
     return db.GetDbSet<Customer>(); 
    } 
} 

Customer不需要有一个地址。如果我查询它像/customers?$expand=Address它不会包括Customers其中Address == null。它只会返回存在Customer.AddressCustomer实体。

我想它做了一个内部连接,因此没有得到没有AddressCustomer实体。 有没有任何方法可以包含地址为空的客户?

电流输出:

[ 
    { 
     Id: 1, 
     Name: 'Customer1', 
     AddressId: 1, 
     Address : 
     { 
      Id: 1, 
      Street: 'Some street' 
     } 
    } 
] 

求购输出:上述

[ 
    { 
     Id: 1, 
     Name: 'Customer1', 
     AddressId: 1, 
     Address : 
     { 
      Id: 1, 
      Street: 'Some street' 
     } 
    }, 
    { 
     Id: 2, 
     Name: 'Customer2', 
     AddressId: null, 
     Address : null 
    } 
] 

这些模型是一个例子。实际上我有更大的模型,但我试图尽可能缩短范例以提供mcve。我已阅读thisthis问题,但我没有收到任何错误。我根本没有得到这些实体。

+0

你的EF查询是什么? – Sampath

+0

我只是将'DbSet'作为查询返回,所以我根本不做任何查询。我将代码添加到示例中。 – smoksnes

回答

0

在使用$expand时,似乎需要的输出是OData服务的正常行为。该错误是由我的映射造成的。

出于某种原因,我有一些旧代码需要Address,即使外键本身是可空的。

public class CustomerMap : EntityTypeConfiguration<Customer> 
{ 
    public CustomerMap() 
    { 
     // Other code... 

     // This is wrong! 
     this.HasReguired(c => c.Address).WithMany(a => a.Customers); 


     // This is right! 
     this.HasOptional(c => c.Address).WithMany(a => a.Customers); 
    } 
} 

因为映射的同时,EF翻译SQL成INNER JOIN而不是一个OUTER JOIN