我有一个服务对象 Update
public bool Update(object original, object modified)
{
var originalClient = (Client)original;
var modifiedClient = (Client)modified;
_context.Clients.Update(originalClient); //<-- throws the error
_context.SaveChanges();
//Variance checking and logging of changes between the modified and original
}
Run Code Online (Sandbox Code Playgroud)
这是我从以下方法调用此方法的地方:
public IActionResult Update(DetailViewModel vm)
{
var originalClient = (Client)_service.GetAsNoTracking(vm.ClientId);
var modifiedClient = (Client)_service.Fetch(vm.ClientId.ToString());
// Changing the modifiedClient here
_service.Update(originalClient, modifiedClient);
}
Run Code Online (Sandbox Code Playgroud)
这是GetAsNotTracking方法:
public Client GetAsNoTracking(long id)
{
return GetClientQueryableObject(id).AsNoTracking().FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)
Fetch 方法:
public object Fetch(string id)
{
long fetchId;
long.TryParse(id, out fetchId); …Run Code Online (Sandbox Code Playgroud) 我正在使用 ASP.NET Core 2.2、EF Core 和 MOQ。正如您在以下代码中所看到的,我有两个测试,并且同时运行,两个数据库名称均为“MovieListDatabase” 我在其中一个测试中出现错误并显示此消息:
Message: System.ArgumentException : An item with the same key has already
been added. Key: 1
Run Code Online (Sandbox Code Playgroud)
如果我分别运行每一个,它们都会通过。
而且,在两个测试中使用不同的数据库名称,例如“MovieListDatabase1”和“MovieListDatabase2”并且同时运行它再次通过。
我有两个问题:为什么会发生这种情况?以及如何重构我的代码以在两个测试中重用内存数据库并使我的测试看起来更简洁?
public class MovieRepositoryTest
{
[Fact]
public void GetAll_WhenCalled_ReturnsAllItems()
{
var options = new DbContextOptionsBuilder<MovieDbContext>()
.UseInMemoryDatabase(databaseName: "MovieListDatabase")
.Options;
// Insert seed data into the database using one instance of the context
using (var context = new MovieDbContext(options))
{
context.Movies.Add(new Movie { Id = 1, Title = "Movie 1", YearOfRelease = 2018, Genre = "Action" }); …Run Code Online (Sandbox Code Playgroud)