【问题标题】:Is it possible to add array of data in child entity?是否可以在子实体中添加数据数组?
【发布时间】:2021-11-21 14:03:58
【问题描述】:

我有一个问题,希望这里的人能够帮助我。对于这个练习,我正在使用 aspnetboilerplate 框架。

所以我创建了 3 个实体,它们都运行良好(至少我猜它们运行良好)

项目回顾

一个 Recepie 有一种或多种成分

Ingrident.cs

    public class Ingrident : Entity
{

    public string Name { get; set; }
    public Master Master { get; set; }

    public int? MasterId { get; set; }

    public Recepie Recepie { get; set; }
    public int? RecepieId { get; set; }

}

Master.cs

    public class Master : Entity
{
    public string Name { get; set; }
    public string? Image { get; set; }
    public string? ShortDescription { get; set; }
    public string? FullDescription { get; set; }
    public string? Keywords { get; set; }
    public string Slug { get; set; }
    public int? Count { get; set; }
    public List<Ingrident> Ingridents { get; set; }
}

Recepie.cs

   public class Recepie : Entity
    {
    public string RecepieName { get; set; }

    public Ingrident Ingridents { get; set; } 
    
    }

有了这个数据库结构,我可以添加 Recepie 并在我尝试发送成分的 [] 时仅添加一种成分,它会显示 DTO 错误。

这里是 RecepieAppService.cs

 public class RecepieAppService : AsyncCrudAppService<IndexIngrident.Entities.Recepie,RecepieDto>
{
    private readonly IRepository<IndexIngrident.Entities.Recepie> _repository;
    private readonly IRepository<IndexIngrident.Entities.Ingrident> _ingRepository;

    public RecepieAppService(IRepository<IndexIngrident.Entities.Recepie> repository, IRepository<IndexIngrident.Entities.Ingrident> ingRepository)
   : base(repository)
    {
        _repository = repository;
        _ingRepository = ingRepository;
    }

    public List<RecepieFullGetDto> GetAllIncluded()
    {
        var result = _repository.GetAllIncluding(x => x.Ingridents , x => x.Ingridents.Master);
        Debug.WriteLine(result);

        return ObjectMapper.Map<List<RecepieFullGetDto>>(result);
    }


}

RecepieDto.cs

    [AutoMap(typeof(IndexIngrident.Entities.Recepie))]

public class RecepieDto : EntityDto
{
    public string RecepieName { get; set; }

    public IngridentRecepieDto Ingridents { get; set; }
}




   public class IngridentRecepieDto : EntityDto
{
    public string Name { get; set; }
    public int RecepieId { get; set; }
}

使用 AsyncCrudAppService 我的 CRUD 会自动生成,我可以创建新的 Recepie,但是当我尝试做这样的事情时

我得到错误

【问题讨论】:

  • RecepieDto 有一个 IngridentRecepieDto,但您传递的是 IngridentRecepieDto 数组。尝试在 RecepieDto 中将 Ingridents 声明为数组。这将破坏 AutoMap,因此您还需要将 Recepie 中的 Ingridents 设为数组,这可能需要更改数据源。长话短说,是的,有可能(一切皆有可能)。
  • Please don't post code, exceptions, or results as images。它们不能被复制(部分)来回答,它们的“文本”不会出现在搜索引擎中。图片只能作为最后的手段。

标签: c# asp.net entity-framework aspnetboilerplate


【解决方案1】:

你需要添加对象的双向映射,[AutoMapTo(typeof(RecepieDto))]和[AutoMapFrom(typeof(Recepie))],并验证你有类,继承AutomapperProfile

【讨论】:

  • 您好,我尝试输入此代码,但它不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-24
  • 2016-05-24
  • 2014-11-30
  • 1970-01-01
  • 2019-08-31
  • 2021-12-13
相关资源
最近更新 更多