您好,最近我将.net core 2.1项目升级到3.1,并开始破坏现有的单元测试用例。我有下面的测试用例。
public async void ShouldAddOrUpdateFxRate_WhenFxRateEntityIsNew()
{
var mockProductsDbContext = ProductsDbContextInMemory();
var currencyMappingId = 12345;
string sourceCurrency = "US_Dollar";
string destination = "NewZealand";
string destinationCurrency = "NZ";
DateTime validFrom = DateTime.UtcNow;
FxRate fxRate = GetFxRate(currencyMappingId, sourceCurrency, destination, destinationCurrency, 0.73M, validFrom, validFrom.AddMonths(2));
mockProductsDbContext.FxRates.Add(fxRate);
mockProductsDbContext.SaveChanges();
contextProviderServiceMock.CreateProductsDbContext().Returns(mockProductsDbContext);
var inputFxrate = new FxRate()
{
ExchangeRate = 12,
ValidFrom = DateTime.Now.AddMonths(3),
ValidTo = DateTime.Now.AddMonths(6),
CurrencyMappingId = currencyMappingId,
CurrencyMapping = new CurrencyMapping
{
DestinationCountry = destination,
SourceCurrency = sourceCurrency,
FromCurrencyCode = "USD",
ToCurrencyCode = destinationCurrency,
Id = currencyMappingId,
}
};
var fxRateRepository = new FxRateRepository(contextProviderServiceMock, loggerMock.Object);
// When
await fxRateRepository.AddOrUpdateFxRate(inputFxrate);
var fxRateEntityCount = await mockProductsDbContext.FxRates.CountAsync();
Assert.Equal<int>(2, fxRateEntityCount);
}
我有以下用于AddOrUpdateFxRate的代码
public async Task AddOrUpdateFxRate(FxRate fxRateDetails)
{
var productsDbContext = this.contextProviderService.CreateProductsDbContext();
try
{
var currencyMapping = await GetCurrencyMapping(fxRateDetails.CurrencyMappingId);
var destinationCountry = Enum.Parse<Country>(currencyMapping.DestinationCountry, true);
var fxRate = await GetFxRate(currencyMapping.SourceCurrency, destinationCountry, fxRateDetails.ValidFrom, fxRateDetails.ValidTo);
if (fxRate == null)
{
productsDbContext.FxRates.Add(fxRateDetails);
}
else
{
if (fxRate.ExchangeRate != fxRateDetails.ExchangeRate)
{
productsDbContext.FxRates.Update(fxRateDetails);
}
else
{
fxRateRepoLogging.LogInformation($"ProductRefApi.FxRateRepo: FxRate Already Present{fxRate.Id} ");
}
}
productsDbContext.Entry(fxRateDetails).State = EntityState.Detached;
await productsDbContext.SaveChangesAsync();
}
catch (Exception ex)
{
throw ex;
}
}
会抛出
System.InvalidOperationException:实体类型的实例 无法跟踪“ CurrencyMapping”,因为具有 {'Id'}的相同键值已被跟踪。连接时 现有实体,请确保只有一个具有给定实体的实体实例 键值已附加。考虑使用 'DbContextOptionsBuilder.EnableSensitiveDataLogging'以查看 冲突的键值。
有人可以帮助我解决此问题吗?任何帮助,将不胜感激。谢谢