c#使用dto转换对象



大家好!我有这些类我填充从db:

public class BaseProduct
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int MainCategoryId { get; set; }
public MainCategory mainCategory { get; set; }
public int MaterialId { get; set; }
public Material material { get; set; }
public ICollection<ProductVariant> productVariants { get; set; }
public ICollection<ImageBase> ImageBases { get; set; }
public int UnitsSold { get; set; }
[Column(TypeName = "decimal(18,2)")]
public decimal Price { get; set; }
public int Discount { get; set; }
[Column(TypeName = "decimal(18,2)")]
public decimal TotalPrice { get; set; }
}
public class ImageBase
{
[Key]
[Column(TypeName = "bigint")]
public long Id { get; set; }
[Column(TypeName ="varchar(max)")]
public string ImagePath { get; set; }
[Column(TypeName ="datetime")]
public DateTime AddedOn { get; set; }
public int BaseProductId { get; set; }
[JsonIgnore]
public BaseProduct baseProduct { get; set; }
//TODO fix typo
public string SaticPath { get; set; }
}

我想把它们转换成这样:

public class BaseProductCustomReturn
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public MainCategory mainCategory { get; set; }
public Material material { get; set; }
public ICollection<ProductVariant> productVariants { get; set; }
public ICollection<BaseImageReturn> ImageBases { get; set; }
public int UnitsSold { get; set; }
[Column(TypeName = "decimal(18,2)")]
public decimal Price { get; set; }
public int Discount { get; set; }
[Column(TypeName = "decimal(18,2)")]
public decimal TotalPrice { get; set; }
}
public class BaseImageReturn
{
[Key]
[Column(TypeName = "bigint")]
public long Id { get; set; }
[Column(TypeName = "datetime")]
public DateTime AddedOn { get; set; }
public int BaseProductId { get; set; }
[JsonIgnore]
public BaseProduct baseProduct { get; set; }
//TODO fix typo
public string StaticPath { get; set; }
}

主要的区别是在BaseProductCustomReturn我有Ienumerable(BaseImageReturn)而不是Ienumerable(ImageBase)

我写了这个dto转换方法

public static IEnumerable<BaseProductCustomReturn> ConvertToDto(this IEnumerable<BaseProduct> baseProducts)
{
var baseProductCustomReturn = (from baseProduct in baseProducts
select new BaseProductCustomReturn
{
Id = baseProduct.Id,
Name = baseProduct.Name,
Description = baseProduct.Description,
mainCategory = baseProduct.mainCategory,
material = baseProduct.material,
productVariants= baseProduct.productVariants,
ImageBases
});
}

正如你所看到的,我被困在转换ImageBase,我如何转换ImageBase到ImageBaseReturn?它们都是列表,所以我不能逐个转换。

你可以使用LINQ

ImageBases = baseProduct.ImageBases.Select(b => new BaseImageReturn(){/* Copy properties */}).ToList()

请注意,dto类型的大部分好处来自于允许您拥有更复杂的模型,而无需考虑序列化问题。比如允许你有私有的setter,和做验证的方法等等。在您的示例中,您的DTO和模型几乎相同,因此您不会获得很大的好处。

如果你正在使用数据库,你也可以考虑使用对象关系映射器(ORM),如实体框架(EF)。

相关内容

  • 没有找到相关文章

最新更新