【问题标题】:One to many relation, pass empty model一对多关系,传递空模型
【发布时间】:2022-01-20 23:13:30
【问题描述】:

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

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; }
  }

客户.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",…} 错误: {Customer.Country: ["The Country field is required."],...} status: 400 title: "发生了一个或多个验证错误。"跟踪标识: “00-98502b075467df5eb3a914a864a96195-c64fbefaa40f2e0f-00”类型: “https://tools.ietf.org/html/rfc7231#section-6.5.1”

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

【问题讨论】:

    标签: c# entity-framework entity-framework-core ef-code-first


    【解决方案1】:

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

    public Guid? CustomerId { get; set; }
    

    【讨论】:

    • 经过进一步调查并从模型中删除[Required],它说Customer = customer,ApplicationUser newUser 中为空。任何想法如何克服这个问题?这是真的,因为我没有指定任何客户,但如何让它工作?提前谢谢!
    • 什么问题?当然 Customer 是空的。
    • 我的意思是如果没有在一对多关系中指定客户,有什么方法可以保存记录?我已经尝试过您的解决方案,但由于Customer = customer 为空,将CustomerId 更改为可空并没有帮助。
    猜你喜欢
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多