【发布时间】:2020-04-07 19:17:02
【问题描述】:
环境:Net Core 3.1 Web Api,Microsoft.AspNetCore.OData 7.4.0-beta
我有一个运行良好的 OData api 控制器 CustomersController,但 $expand 总是返回 NullReferenceException。客户有一对多的联系人和地址。
这是动作方法的代码:
[HttpGet]
[ODataRoute]
[EnableQuery]
public IActionResult Get()
{
try
{
var customers = _context.Customers;
_logger.LogInfo($"Returned {customers.Count()} customers from database.");
return Ok(customers);
}
catch (Exception ex)
{
_logger.LogError($"Something went wrong inside Get customers action: {ex.Message}");
return StatusCode(500, "Internal server error");
}
}
这是客户对象定义:
public class Customer : BaseEntity
{
public Guid CustomerId { get; set; }
[Required(ErrorMessage = "Name is required")]
[StringLength(100, ErrorMessage = "Name can't be longer than 100 characters")]
public string Name { get; set; }
[StringLength(100, ErrorMessage = "Commercial name can't be longer than 100 characters")]
public string CommercialName { get; set; }
[Required(ErrorMessage = "Tax code is required")]
[StringLength(25, ErrorMessage = "Tax code can't be longer than 25 characters")]
public string TaxCode { get; set; }
[StringLength(250, ErrorMessage = "Email can't be longer than 250 characters")]
[EmailAddress]
public string Email { get; set; }
[StringLength(250, ErrorMessage = "Url can't be longer than 250 characters")]
public string Url { get; set; }
public ICollection<Contact> Contacts { get; set; }
public ICollection<Address> Addresses { get; set; }
public ICollection<Work> Works { get; set; }
}
DbContext 配置:
// Table
builder.ToTable("Customers");
builder.HasKey(b => b.CustomerId);
// Relationships
builder.HasMany(b => b.Contacts)
.WithOne(b => b.Customer)
.HasForeignKey(b => b.CustomerId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasMany(b => b.Addresses)
.WithOne(b => b.Customer)
.HasForeignKey(b => b.CustomerId)
.OnDelete(DeleteBehavior.Cascade);
我有另一个控制器,但具有一对一的关系,并且此控制器可以与 $expand 一起正常工作,并在操作方法中使用相同的代码。
知道什么是失败的吗? 问候
【问题讨论】:
标签: odata asp.net-core-webapi nullreferenceexception asp.net-core-3.1