Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DBContext.Entry(newEntity).CurrentValues.SetValues(oldEntity) throws InvalidOperationException #6

Open
fieldb opened this issue Apr 15, 2015 · 0 comments

Comments

@fieldb
Copy link

fieldb commented Apr 15, 2015

The following code runs in production but throws an InvalidOperationException in the unit test when DBSet (Materials) is a MockDBSet. Here is the setup for the mocks:

var items = new List<Material> {
  new Material { Id = 1, Pieces = 10 },
  new Material {Id = 2, Pieces = 10 }
};

var mockItems = new MockDBSet<Material>()
 .SetupSeedData(items)
 .SetupAddAndRemove()
 .SetupLinq();

var mockContext = new Mock<MyContext>();
mockContext.Setup(o=>o.Materials).Returns(mockItems.Object);

The mockContext is then passed to a service. Here is the code within the service that throws the exception:

var items = _context.Materials.ToList();
var newItem = new Material();
var oldItem = items.First();
_context.Materials.Add(newItem);           
_context.Entry(newItem).CurrentValues.SetValues(oldItem);

Here is the exception:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Member 'CurrentValues' cannot be called for the entity of type 'Material' because the entity does not exist in the context. To add an entity to the context call the Add or Attach method of DbSet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant