C# 将对象数组添加到 ICollection - 转换 dto -> 模型

标签 c# dto icollection

我需要转换这个 DTO

public class MyDTO
{
   [JsonProperty("studentInfo")]
   public StudentInfo studentInfo {get; set; }

   public class StudentInfo
   { 
      [JsonProperty("others")]
      public ICollection<AnotherDTO[]> Others { get; set; }
   }
   public class AnotherDTO
   {
       [JsonProperty("name")]
       public string name { get; set; }
   }

}

此模型

public class MyModel
{
   public StudentInfo studentInfo {get; set; }

   public class StudentInfo
   { 
      public ICollection<Another[]> Others { get; set; }
   }
   public class Another
   {
       public string name { get; set; }
   }

}

我对 ICollection 很着迷。这是我尝试填充其他 ICollection 的部分。

 private static ICollection<MyModel.Another[]> getAnothers(MyDTO myDTO, MyModel myModel)
 {  
    List<MyModel.Another> myList = new List<MyModel.Another>();
    foreach(var x in myDTO.studentInfo.Others)
    {
      foreach(var y in x)
      {
         myList.Add(new MyModel.Another
         {
             name = y.name
         });
      }

    }
 }
 MyModel.Another[] newList;
 newList = myList.ToArray();
 ICollection<MyDTO.AnotherDTO[]> ic = (ICollection<MyModel.Another[]>newList.Cast<MyModel.Another[]>().ToList();

最后一行给我以下错误:

无法将 MyModel 类型的对象转换为 MyModel[] 类型。

如果有任何帮助,我将不胜感激。

最佳答案

我建议使用AutoMapper,而不是手动映射对象。 。 AutoMapper 是一个简单的小库,旨在解决一个看似复杂的问题 - 摆脱将一个对象映射到另一个对象的代码。您还可以获取 AutoMapper 的 Nuget 包

只需定义对象的映射 -

Mapper.CreateMap<MyDTO, MyModel>();

..然后像这样简单地映射对象 -

var myModelObject = Mapper.Map<MyModel>(myDtoObject);

请引用this入门链接。

关于C# 将对象数组添加到 ICollection - 转换 dto -> 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33116256/

相关文章:

java - 从我的 DTO 创建列表

c# - 如何判断 ParameterInfo 类型是否为集合?

c# - 如何隐藏接口(interface)的某些成员

c# - DefaultValueAttribute 似乎没有效果

c# - 如何为 SQL 查询编写自动化测试?

c# - 是否可以从 FileResult 获取 byte[]?

java - 在不知道来自前端和 JSON 的数据库 ID 的情况下将子实体分配给父实体

javascript - NestJS 中用于键值对对象的 ValidationPipe

c# - 如何在 powershell 中的单行上设置 Set-VMFirmware

c# - 在 C# 中设置 ICollection 属性的值