Halcyon Halcyon - 1 year ago 226
C# Question

Reload a Saved Entity Using Moq, NUnit and Entity Framework

I'm have a unit test (using NUnit) and I'm trying to mock an add operation in Entity Framework 6. In the add operation, I add a new person entity and reload it so the newly created id can be returned. The problem I run into is when I want to reload the entity, I get the error, "The model backing the context has changed since the database was created". All of the answers on Google that I've checked do not have any solutions when applied to a mocking scenario.

public void Add()
var person = new Person
FirstName = "John",
LastName = "Doe",
Dob = new DateTime(1984, 8, 23),
Ssn = "555-55-5555"

var mockDbSet = new Mock<DbSet<Person>>();
mockDbSet.Setup(s => s.Create()).Returns(new Person());

var mockContext = new Mock<PersonContext>();
mockContext.Setup(c => c.People).Returns(mockDbSet.Object);


// This code will throw an error.

mockDbSet.Verify(m => m.Add(It.IsAny<Person>()), Times.Once());
mockContext.Verify(m => m.SaveChanges(), Times.Once());

// To do: Test that the id was populated from the reload operation.

What can I do to reload the entity and retrieve the new id?

Answer Source

I figured out that I was using old code from EF 5. I updated this answer to include both methods.

// This is how to return a newly inserted id from EF 6.
public int AddMyEntity(MyEntity myEntity)
    return myEntity.Id; 

// This is how to return a newly inserted id from EF 5.
public int AddMyEntity(MyEntity myEntity)
    return myEntity.Id; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download