简体   繁体   English

可空外键

[英]Nullable Foreign Keys

I have an Orders wpf grid, this view includes 2 foreign keys, Customers and Vendors.我有一个 Orders wpf 网格,这个视图包括 2 个外键,客户和供应商。 The Create Orders View includes these 2 foreign keys too, as well as imports extra info like vendor id and name and phone number. Create Orders 视图也包括这两个外键,以及导入额外的信息,如供应商 ID、姓名和电话号码。

It is not always necessary to fill out the vendor on this view, however everything I've tried doesn't allow the vendor to be null.并不总是需要在此视图上填写供应商,但是我尝试的所有方法都不允许供应商是 null。

I've tried stuff like this but the flow here doesn't match my case, and can't seem to access the right properties when trying to manipulate the flow.我已经尝试过这样的东西,但这里的流程与我的情况不匹配,并且在尝试操纵流程时似乎无法访问正确的属性。 https://stackoverflow.com/a/49652484/4583310 https://stackoverflow.com/a/49652484/4583310

putting "?"把“?” after my variables is giving foreign key errors as well.在我的变量也给出外键错误之后。

how can I get this baby to accept null values?我怎样才能让这个宝贝接受 null 值?

 public readonly struct CreateOrderRequest
{
    //[Required]
    public int VendorId { get; init; }
    [Required]
    public int CustomerId { get; init; }
    public string SearchUrl { get; init; }
}


 public class Order
{
    [Key]
    public int Id { get; set; }
    public string Description { get; set; }            

    [ForeignKey(nameof(Vendor))]
    public int VendorId { get; set; }
    public Vendor Vendor { get; set; }
    public string SearchUrl { get; set; }

    [ForeignKey(nameof(Customer))]
    public int CustomerId { get; set; }
    public Customer Customer { get; set; }
}

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
       // modelBuilder.Entity<Order>().HasMany(a => Vendor);
        OnModelCreatingPartial(modelBuilder);
    }

I get errors on the await command我在 await 命令上遇到错误

  public async Task<Order> CreateOrderAsync(Order order)
    {
        var entry = await _ordersDbSet.AddAsync(order);
        await _dbContext.SaveChangesAsync();
        return entry.Entity;
    }

which stem from trying to post from the orders controller.这源于试图从 controller 订单中发布。 I turned off validating the vendor我关闭了验证供应商

 public async Task<IActionResult> CreateOrderAsync(CreateOrderRequest request)
    {
        if (await ValidateCreateOrderRequestAsync(request) is false)
            return BadRequest();

        var order = _mapper.Map<Order>(request);
        order = await _ordersUnitOfWork.CreateOrderAsync(order);
        order = await _ordersUnitOfWork.GetOrderAsync(order.Id);

        var orderDto = _mapper.Map<OrderDto>(order);
        return Ok(orderDto);
    }

nullable foreign key is not a good idea at all but some times we have to use it.可空外键根本不是一个好主意,但有时我们必须使用它。 you can use it by changing你可以通过改变来使用它

public int VendorId { get; set; }

to

public int? VendorId { get; set; }

in Order class按顺序 class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM