【问题标题】:How to map a field to a new instance of a class?如何将字段映射到类的新实例?
【发布时间】:2019-12-02 15:02:58
【问题描述】:

我正在编写一个 ASP.NET Core WebAPI 项目,但映射有问题。由于我无法在 Entity Framework Core 中创建基元集合,因此我创建了一个存储所需基元的实体。但在上层,我真的不需要一个带有原语的单独类。是否可以从一个类创建一个 Map 到一个基元(为了方便使用)并返回(将它们存储在 DB 中)?

Realtor.cs

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

    [Required]
    [MaxLength(20)]
    public string FirstName { get; set; }

    [Required]
    [MaxLength(20)]
    public string SecondName { get; set; }

    [Required]
    [MaxLength(20)]
    public string LastName { get; set; }

    [Required]
    public ICollection<PhoneNumber> Numbers { get; set; }

    [ForeignKey("Photo")]
    public int PhotoId { get; set; }
    public Image Photo { get; set; }
}

PhoneNumber.cs(具有原语的类)

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

    [Required]
    [StringLength(13, MinimumLength = 10)]
    public string Number { get; set; }

Realtor.cs(在业务层)

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string SecondName { get; set; }
    public string LastName { get; set; }
    public ICollection<string> Numbers { get; set; }
    public int PhotoId { get; set; }
    public Image Photo { get; set; }

所以我需要在这里将ICollection&lt;PhoneNumber&gt; 绑定到ICollection&lt;string&gt;。还是不这样做会更好?

【问题讨论】:

  • 当您只需要电话号码列表时,请使用 ICollection 。如果您想在将来扩展您的电话号码,请使用您的 ICollection 方法。

标签: c# .net-core entity-framework-core automapper asp.net-core-webapi


【解决方案1】:

可以将映射到IEnumerable&lt;string&gt; 用于显示等,但如果您添加或修改,您应该坚持使用List&lt;PhoneNumber&gt;。这是因为每个电话号码的 PK 至关重要。否则,您最终会添加新的(即重复的)电话号码记录,而不是修改现有的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 2020-10-24
    • 2020-09-20
    • 2022-12-07
    • 1970-01-01
    相关资源
    最近更新 更多