[英]OData $expand does not include entities where expanded property is null
I have an OData service build with WebAPI and EF 6. I use the fluent api to create my models. 我有一个使用WebAPI和EF 6的OData服务构建。我使用流畅的api来创建我的模型。 It works fine, but when I use
$expand
it omits entities where the expanded property is null
. 它运行正常,但是当我使用
$expand
它会省略扩展属性为null
实体。
This is a simplified example: 这是一个简化的例子:
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>();
}
}
A Customer
doesn't need to have an address. Customer
无需拥有地址。 And If I query it like /customers?$expand=Address
it will not include Customers
where Address == null
. 如果我像
/customers?$expand=Address
那样查询它/customers?$expand=Address
它将不包括Address == null
Customers
。 It will only return the Customer
entities where Customer.Address
exists. 它只会返回
Customer
那里实体Customer.Address
存在。
I guess it does an inner join, and therefore doesn't get the Customer
entities that doesn't have an Address
. 我猜它会进行内连接,因此不会获得没有
Address
的Customer
实体。 Is there any way to include customers where address is null as well? 有没有办法包括地址为空的客户?
Current Output: 电流输出:
[
{
Id: 1,
Name: 'Customer1',
AddressId: 1,
Address :
{
Id: 1,
Street: 'Some street'
}
}
]
Wanted output: 通缉输出:
[
{
Id: 1,
Name: 'Customer1',
AddressId: 1,
Address :
{
Id: 1,
Street: 'Some street'
}
},
{
Id: 2,
Name: 'Customer2',
AddressId: null,
Address : null
}
]
The models above is an example. 以上模型就是一个例子。 I actually got way bigger models, but I tried to keep the example as short as possible to provide a mcve .
我实际上得到了更大的模型,但我试图尽可能地缩短示例以提供一个mcve 。 I've read this and this question, but I'm not getting any error.
我已经阅读了这个和这个问题,但我没有收到任何错误。 I just don't get the entities at all.
我根本没有获得实体。
It appeared that the wanted output is the normal behavior for an OData service when using $expand
. 当使用
$expand
时,看起来想要的输出是OData服务的正常行为。 The error was caused by my mappings. 错误是由我的映射引起的。
For some reason I had a bit of old code that made the Address
required, even though the foreign key itself was nullable. 出于某种原因,我有一些旧代码使得
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);
}
}
And because of the mapping, EF translated the SQL into an INNER JOIN
instead of an OUTER JOIN
. 由于映射,EF将SQL转换为
INNER JOIN
而不是OUTER JOIN
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.