我正在尝试使用继承自 ApplicationUser
的单独身份类,并在它们之间创建关系。企业和客户,企业可以拥有许多客户。添加关系时出现错误。实现在具有关系的类之间添加身份的正确方法是什么?
ApplicationUser.cs
public class ApplicationUser : IdentityUser
{
public virtual Business Business { get; set; }
public virtual Customer Customer { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
}
Business.cs
public class Business : ApplicationUser
{
public string BusinessUserId { get; set; }
[Required]
public string BusinessName { get; set; }
[Required]
[Display(Name = "Address")]
public string Address { get; set; }
public ICollection<Customer> Customers { get; set; }
....
}
Customer.cs
public class Customer : ApplicationUser
{
public string CustomerUserId { get; set; }
public override Business Business { get; set; }
}
最佳答案
您正在使用 TPH,它将进入上述实体的同一个表 (AspNetUser)。
要使用 TPT,您可以配置如下模型
public class ApplicationUser : IdentityUser
{
public string BusinessId { get; set; }
[ForeignKey("BusinessId")]
public virtual Business Business { get; set; }
public string CustomerId { get; set; }
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
}
public class Business
{
[Key]
public string BusinessUserId { get; set; }
[Required]
public string BusinessName { get; set; }
[Required]
[Display(Name = "Address")]
public string Address { get; set; }
public virtual ApplicationUser User { get; set; }
public ICollection<Customer> Customers { get; set; }
}
public class Customer
{
[Key]
public string CustomerUserId { get; set; }
public string BusinessId { get; set; }
[ForeignKey("BusinessId")]
public Business Business { get; set; }
public virtual ApplicationUser User { get; set; }
}
数据库上下文:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Customer> Customers { get; set; }
public DbSet<Business> Businesses { get; set; }
}
关于asp.net - 实体类型 'Customer' 无法映射到表,因为它是从 'ApplicationUser' 派生的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59558083/