【问题标题】:About .net core one-to-many association关于 .net core 一对多关联
【发布时间】:2021-09-20 11:02:14
【问题描述】:

我正在使用.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);

【问题讨论】:

标签: .net asp.net-core .net-core entity-framework-core entity-relationship


【解决方案1】:

试试这个

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    相关资源
    最近更新 更多