实体类型'Customer'无法映射到表,因为它派生自'ApplicationUser'

问题描述 投票:0回答:1

我正在尝试使用从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; }
    }
asp.net asp.net-mvc asp.net-core
1个回答
0
投票

您正在使用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; }
}

DbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {

    }


    public DbSet<Customer> Customers { get; set; }
    public DbSet<Business> Businesses { get; set; }

}
© www.soinside.com 2019 - 2024. All rights reserved.