我需要添加图片并将图片ID和产品ID存储在单独的productPicture表中。没有现有产品,您无法添加图片。如何实现呢?
这是我向数据库添加实体的代码:
控制器:
[HttpPost]
[Route("api/v1/catalog/products/pictures")]
[ProducesResponseType((int)HttpStatusCode.Created)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> UploadPicture([FromForm]PictureViewModel pic)
{
try
{
var result = await _service.Add(pic);
if (result.HasErrors)
{
return BadRequest(result.Errors);
}
return CreatedAtAction(nameof(GetById), result);
}
catch (Exception ex)
{
return BadRequest(ex.ToString());
}
}
服务:
public async Task<ServiceResultWithoutBaseEntity<Picture>> Add(PictureViewModel newItem)
{
var result = new ServiceResultWithoutBaseEntity<Picture>();
result.Errors.AddRange(Validate(newItem));
if (result.HasErrors)
return result;
var item = await newItem.MapToEntity(new Picture());
_context.Pictures.Add(item);
await _context.SaveChangesAsync();
result.EntityResult = item;
return result;
}
助手:
public async static Task<Picture> MapToEntity(this PictureViewModel source, Picture entity)
{
if (source == null || entity == null)
return null;
if (source.FileForUpload != null || source.FileForUpload.Length != 0)
{
AzureBlobExtensions abe = new AzureBlobExtensions();
string folderValue = string.Concat(entity.ID.ToString().ToLower(), "/", DateTime.Now.ToString("yyyyMMddHHmmss"), source.FileForUpload.FileName);
var fileUrl = await abe.UploadFile(source.FileForUpload, folderValue, Path.GetExtension(source.FileForUpload.FileName), "Picture");
entity.VirtualPath = fileUrl;
}
else
{
entity.VirtualPath = source.FileUrl;
}
entity.FileName = source.FileName;
entity.SeoFilename = source.SeoFilename;
entity.AltAttribute = source.AltAttribute;
entity.TitleAtrribute = source.TitleAtrribute;
entity.MimeType = source.MimeType;
entity.IsNew = source.IsNew;
return entity;
}
productPicture表