为Services项目添加项目引用,引用RepositoryContracts
更新CountriesService.cs以使用Repository
using Entities;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using OfficeOpenXml;
using RepositoryContracts;
using ServiceContracts;
using ServiceContracts.DTO;
namespace Services
{
public class CountriesService : ICountriesService
{
//private field
private readonly ICountriesRepository _countriesRepository;
//constructor
public CountriesService(ICountriesRepository countriesRepository)
{
_countriesRepository = countriesRepository;
}
public async Task<CountryResponse> AddCountry(CountryAddRequest?
countryAddRequest)
{
//Validation: countryAddRequest parameter can't be null
if (countryAddRequest == null)
{
throw new ArgumentNullException(nameof(countryAddRequest));
}
//Validation: CountryName can't be null
if (countryAddRequest.CountryName == null)
{
throw new
ArgumentException(nameof(countryAddRequest.CountryName));
}
//Validation: CountryName can't be duplicate
if (await
_countriesRepository.GetCountryByCountryNameAsync(countryAddRequest.CountryName)
!= null)
{
throw new ArgumentException("Given CountryName already exists!");
}
//Convert object from CountryAddRequest to Country type
Country country = countryAddRequest.ToCountry();
//generate CountryId
country.CountryId = Guid.NewGuid();
//Add country object into _db
await _countriesRepository.AddCountryAsync(country);
return country.ToCountryResponse();
}
public async Task<List<CountryResponse>> GetAllCountries()
{
//Convert all countries from "Country" type to "CountryResponse" Type
return (await
_countriesRepository.GetAllCountriesAsync()).Select(country =>
country.ToCountryResponse()).ToList();
//Return all CountryResponse objects
}
public async Task<CountryResponse?> GetCountryByCountryId(Guid?
countryId)
{
if (countryId == null)
{
return null;
}
Country? country = await
_countriesRepository.GetCountryByCountryIdAsync(countryId.Value);
if (country == null)
{
return null;
}
return country.ToCountryResponse();
}
public async Task<int> UploadCountriesFromExcelFile(IFormFile fromFile)
{
int countriesInserted = 0;
MemoryStream memoryStream = new MemoryStream();
await fromFile.CopyToAsync(memoryStream);
using (ExcelPackage excelPackage = new ExcelPackage(memoryStream))
{
ExcelWorksheet worksheet =
excelPackage.Workbook.Worksheets["Countries"];
int rowCount = worksheet.Dimension.Rows;
for (int i = 2; i <= rowCount; i++)
{
string? cellValue = Convert.ToString(worksheet.Cells[i,
1].Value);
if (!string.IsNullOrEmpty(cellValue))
{
string countryName = cellValue;
if (await
_countriesRepository.GetCountryByCountryNameAsync(countryName) == null)
{
Country country = new Country()
{
CountryId = Guid.NewGuid(),
CountryName = countryName,
};
await _countriesRepository.AddCountryAsync(country);
countriesInserted++;
}
}
}
}
return countriesInserted;
}
}
}
Gitee获取源码: