链接表ID的API返回空值



这是我遇到很多麻烦的问题,非常感谢您的帮助。

我创建了一个链接到客户ID和手机ID的"新购买" API。但是,当我在数据库中手动填充"购买"表并在Postman上检查此API的获取功能时,它将返回客户和手机ID的null值:

<Purchase>
 <CommissionGenerated>100</CommissionGenerated>
 <Customer i:nil="true"/>
 <DatePurchased>2018-02-15T00:00:00</DatePurchased>
 <Handset i:nil="true"/>
 <Id>3</Id>
</Purchase>

此外,当我尝试发布邮递员时,我会收到一个500个内部服务器错误"无法创建类型'system.collections.generic.generic.list的null常数值....只有实体类型,枚举类型或原始类型在这种情况下支持类型。"

这是我的新手:

public int CustomerId { get; set; }
    public List<int> HandsetIds { get; set; }

这是我的newPurchasesController(API控制器(:

 public class NewPurchasesController : ApiController
{
    private ApplicationDbContext _context;
    public NewPurchasesController()
    {
        _context = new ApplicationDbContext();
    }
    // Get Api/NewPurchases
    public IHttpActionResult GetHandsets(NewPurchaseDto newPurchase)
    {
        var handsetsQuery = _context.Purchases.ToList();
        return Ok(handsetsQuery);
    }
    [HttpPost]
    public IHttpActionResult CreateNewPurchases(NewPurchaseDto newPurchase)
    {
        var customer = _context.Customers.Single(
        c => c.Id == newPurchase.CustomerId);
        var handsets = _context.Handsets.Where(
        m => newPurchase.HandsetIds.Contains(m.Id)).ToList();
        foreach (var handset in handsets)
        {
            var purchase = new Purchase
            {
                Customer = customer,
                Handset = handset,
                DatePurchased = DateTime.Now
            };
            _context.Purchases.Add(purchase);
        }
        _context.SaveChanges();
        return Ok();
    }
}
}

此外,这是我的客户和手机模型:

public class Customer
{
    public int Id { get; set;}
    [Required]
    [StringLength(255)]
    public string Name { get; set; }
    public bool IsSubscribedToInsurance { get; set; }
    [Display(Name = "Account Type")]
    public AccountType AccountType { get; set; }
    public byte AccountTypeId { get; set; }
    [Display(Name = "Date of Birth")]
    [Min18YearsIfAContract]
    public DateTime? Birthdate { get; set; }
}

public class Handset
{
    public int Id { get; set; }
    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    public Manufacturer Manufacturer { get; set; }
    [Display(Name = "Manufacturer")]
    [Required]
    public byte ManufacturerId { get; set; }
    public DateTime DateAdded { get; set; }
    [Display(Name = "Release Date")]
    public DateTime ReleaseDate { get; set; }
    [Display(Name = "Number in Stock")]
    [Range(1, 25)]
    public byte NumberInStock { get; set; }
}

我真的很想进入底部,谢谢!

API和参数看起来不错,当我通过时我可以进入操作:

{
    customerId: 123,
    handsetIds: [1,2,3]
}

因此,它在CreateNewPurchases内部失败。我怀疑这条线

var handsets = _context.Handsets.Where(
    m => newPurchase.HandsetIds.Contains(m.Id)).ToList();

失败了,因为您正在数据库中搜索它们在ID的null List<>中的手机,而SQL无法转换。

将行更改为

var handsets = _context.Handsets.Where(
    m => newPurchase.HandsetIds.Any(np => np == m.Id));

最新更新