【发布时间】: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