关于.net core一对多关联

About .net core one-to-many association

我正在使用.net core,我想在数据库中进行关联。

一个客户可以有多个“治疗”记录。我怎样才能列出它? 所以我想列出一个客户的治疗记录。你能帮忙吗?

型号/Customer.cs

public class Customer
{
    public int Id { get; set; }

    [StringLength(50)]
    public string Name { get; set; }

    [StringLength(50)]
    public string Surname { get; set; }

    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [StringLength(50)]
    public string BusinessCode { get; set; }
}

dtos 文件夹中的文件“GetCustomerDto.cs”

Dtos/Customer/GetCustomerDto.cs

public class GetCustomerDto
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Surname { get; set; }

    public string Email { get; set; }

    public string BusinessCode { get; set; }
}

"Treatment.cs" 模型文件夹中的文件

型号/Treatment.cs

public class Treatment
{
    public int Id { get; set; }


    [Required]
    [StringLength(25)]
    public string UserId { get; set; }

    [StringLength(100)]
    public string ToothNumber { get; set; }

    [StringLength(100)]
    public string ToothGroup { get; set; }

    [DataType(DataType.Text)]
    public string Operation { get; set; }

    [DataType(DataType.Text)]
    public string Action { get; set; }
}




     var dbCustomer = await _context.Customers.Where(c => c.UserId == UserId)
                                                     .Include(c => c.Treatments)
                                                     .FirstOrDefaultAsync(c => c.Id == id);

试试这个

public class Customer
{

[Key]    
public int Id { get; set; }
.....

[InverseProperty(nameof(Treatment.Customer))]
 public virtual ICollection<Treatment> Treatments { get; set; }  
}
public class Treatment
{
    public int Id { get; set; }
 

    public int CustomerId { get; set; }
    [ForeignKey(nameof(CustomerId))]
    [InverseProperty("Treatments")]
    public virtual Customer Customer { get; set; }

    .........

}

如果您使用 net 5+,请修复您的查询

var customers = await _context.Customers
                   .Include(c => c.Treatments.Where(c => c.UserId == UserId))
                   .FirstOrDefaultAsync(c => c.Id == id);