Halcyon Halcyon - 3 months ago 29
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.

[Test]
[Description("Add")]
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);

context.Object.People.Add(person);
context.Object.SaveChanges();

// This code will throw an error.
//context.Object.Entry(person).Reload();

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

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)
{
    dbContext.MyEntities.Add(myEntity);
    context.SaveChanges();
    return myEntity.Id; 
}

// This is how to return a newly inserted id from EF 5.
public int AddMyEntity(MyEntity myEntity)
{
    dbContext.MyEntities.Add(myEntity);
    dbContext.SaveChanges();
    dbContext.Entry(myEntity).Reload();
    return myEntity.Id; 
}