一对多关系,传递空模型

One to many relation, pass empty model

我想将用户分配给某个公司(等于下面的客户)。为此,我创建了一个模型如下:

ApplicationUser.cs:

 public class ApplicationUser : IdentityUser<Guid>
  {
    public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Guid CustomerId { get; set; }
    public Customer Customer { get; set; }
  }

Customer.cs:

  public class Customer
  {
    public Guid Id { get; set; }
    public string CompanyName { get; set; }

    [JsonIgnore]
    public virtual ICollection<ApplicationUser> ApplicationUsers { get; set; }

  }

然后在ApplicationDBContext中添加如下:

  builder.Entity<ApplicationUser>()
  .HasOne<Customer>(s => s.Customer)
  .WithMany(u => u.ApplicationUsers)
  .HasForeignKey(u => u.CustomerId)
  .IsRequired(false)
  .OnDelete(DeleteBehavior.Restrict);

现在,当我尝试创建新用户时,我需要定义客户

  Customer customer = this.Context.Customers.FirstOrDefault(c => c.Id == model.Customer.Id);
  ApplicationUser newUser = new ApplicationUser
  {
    UserName = model.Email,
    Customer = customer,
    CustomerId = customer.Id,
  };

否则我会出错。在上面的示例代码中,我的客户为空。如何在没有客户的情况下输入用户?我的意思是如果它只是普通用户,如管理员、版主等?

这是我从 Json 得到的:

{type: "https://tools.ietf.org/html/rfc7231#section-6.5.1",…} errors: {Customer.Country: ["The Country field is required."],…} status: 400 title: "One or more validation errors occurred." traceId: "00-98502b075467df5eb3a914a864a96195-c64fbefaa40f2e0f-00" type: "https://tools.ietf.org/html/rfc7231#section-6.5.1"

出于验证目的,我已将此字段设置为 [Required]

值类型为 属性 的可选外键必须可为空。例如

public Guid? CustomerId { get; set; }