如何为每个inMemory数据库使用不同的ChangeTracker实例?



我正在尝试使用InMemory数据库来帮助测试我的方法。

我在测试中运行多个datarow时遇到了麻烦,因为除了一个之外,所有这些都会在尝试向上下文添加默认记录时给我一个错误。如果我手动单独运行每个测试,它们都通过了,但是当我运行整个测试时,它们都失败了,只有一个到达mCntx.Brokers.Add(new() ...,并出现以下错误。

System.InvalidOperationException: 'The instance of entity type 'Broker' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'

我已经尝试设置一个新的Db名称,但它似乎仍然从相同的ChangeTracker绘制。

<<p>测试代码/em>
[TestMethod()]
[DataRow(null, _ValidBrokerNameNotInDb, _ValidBrokerageIdInDb, _ValidBrokerageNameInDb)]
[DataRow(null, _ValidBrokerNameNotInDb, null, _ValidBrokerageNameInDb)]
[DataRow(null, _ValidBrokerNameNotInDb, _ValidBrokerageIdInDb, null)]
[DataRow(null, _ValidBrokerNameNotInDb, null, _ValidBrokerageNameNotInDb)]
public void BrokerValidationTest_CreateInDb(int? brokerId, string brokerName, int? brokerageId, string brokerageName)
{
DataTable dataTable = GetDataTable(brokerId, brokerName, brokerageId, brokerageName);
List<UploadIssue> uploadIssues = new();
var rand = new Random().NextDouble();
using (SqlDboDbContext cntx = GetContext($"BrokerValidationTest_CreateInDb{rand}"))
{
InsertUpdateDatabaseService.ImportBroker(dataTable, cntx, ref uploadIssues);
cntx.ChangeTracker.Clear();
}
Assert.IsFalse(uploadIssues.Any(x => x.UploadIssueType == UploadIssueTypes.Error));
Assert.IsFalse(uploadIssues.Any(x => x.UploadIssueType == UploadIssueTypes.DependencyError));
Assert.IsFalse(uploadIssues.Any(x => x.UploadIssueType == UploadIssueTypes.Prompt));
}
public static SqlDboDbContext GetContext(string dbName)
{
var rand = new Random().NextDouble();
var options = new DbContextOptionsBuilder<SqlDboDbContext>()
.UseInMemoryDatabase(databaseName: dbName + rand.ToString())
.Options;
SqlDboDbContext mCntx = new SqlDboDbContext(options);
mCntx.Brokers.Add(new()
{
Id = _ValidBrokerIdInDb,
Name = _ValidBrokerNameInDb,
BrokerageId = _ValidBrokerageIdInDb,
Brokerage = DbBrokerage
});
mCntx.SaveChanges();
return mCntx;
}

问题似乎是与Brokerage = DbBrokerage

private static Brokerage DbBrokerage = new()
{
Id = _ValidBrokerageIdInDb,
Name = _ValidBrokerageNameInDb
};

一旦我将它更改为创建经纪的新实例而不是使用静态实例,它就开始工作了。

mCntx.Brokers.Add(new()
{
Id = _ValidBrokerIdInDb,
Name = _ValidBrokerNameInDb,
BrokerageId = _ValidBrokerageIdInDb,
Brokerage = DbBrokerage
});

mCntx.Brokers.Add(new()
{
Id = _ValidBrokerIdInDb,
Name = _ValidBrokerNameInDb,
BrokerageId = _ValidBrokerageIdInDb,
Brokerage = new()
{
Id = _ValidBrokerageIdInDb,
Name = _ValidBrokerageNameInDb
}
});

相关内容

  • 没有找到相关文章

最新更新