10101
10101

Reputation: 2412

One to many relation, pass empty model

I would like to assign users to certain company (equals Customer below). For this matter I have created a models as follows:

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

  }

Then in ApplicationDBContext added following:

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

Now when I am trying to create a new user I need to have Customer defined

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

otherwise I am getting an error. In above example code my Customer is null. How I can input a user without Customer? I mean if it is just a general user like admin, moderator etc.?

Here is what I get from 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"

I have set this field as [Required] for validation purposes.

Upvotes: 0

Views: 151

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89361

An optional Foreign Key with a value type property must be nullable. eg

public Guid? CustomerId { get; set; }

Upvotes: 1

Related Questions