Reputation: 544
I was doing some tests about repository pattern applied to Entity Framework, when a problem comes out. I have implemented (via code-first) a core-layer and data-layer of an imaginary hotel manager software (called HotelManager) that i'd like to use for testing purposes and that relates with a bunch of table to DB.
This is the structure:
The core-layer stays in the HotelManager.Core assembly and contains:
.
The data-layer stays in the HotelManager.Data assembly and contains:
As you can see, the data-layer exposes an Unit of work class that client applications uses to manipulate data, but here i noticed a strange behavior. In fact all repositories contained into my UoW loads correctly, but adding and removing operations doesn't work at all!
For example:
[TestMethod]
public void AddWontWork()
{
int firstCount = this._hotelManagerUoW.Utenti.AsEnumerable().Count();
AddUser();
int lastCount = this._hotelManagerUoW.Utenti.AsEnumerable().Count();
Assert.IsTrue(lastCount == firstCount + 1);
}
private void AddUser()
{
Utente utente = new Utente();
utente.Nome = "Alex";
utente.Cognome = "DeLarge";
utente.Indirizzo = "London st.";
utente.Nazione = "England";
utente.Password = "mypassword";
utente.Username = "MyUsername";
utente.ZipCode = "784521";
utente.Citta = "Coventry";
this._hotelManagerUoW.Utenti.Add(utente);
}
This test method 'll fail!
I don't know why but even after AddUser()
method has been called (AddUser()
actually adds to the Utenti
repository an instance of a new utente
object), lastCount
matches to firstCount
, like nothing has been happened, and the test fails! I can't even find my brand new added entity into the DbSet managed by my repository! I have the same result when i remove an entity from a repository. Nothing happens. This 'll work only if i call SaveChanges() method after each Add() or Remove() operation but this is not possible, because i need to have the chance to rollback data and because i want to interact with DB only in certain, well-defined cases to reduce DB access the least possible.
Is this the correct behavior of EF and i have completely misunderstood its behavior or there is something wrong in my project?
I always thought that if i run something like UtentiDbSet.Add(new Utente() with {....});
, EF engine adds my new Utente object to the DbSet in an "Added" state (and so, UtentiDbSet.Count() == 1), and then, if i call SaveChanges() of my context, the data 'll be persisted to DB.
For your convenience i've uploaded whole project here.
There's a test project called HotelManager.Data.Test.
I can't understand why AddWontWork()
method fails, while AddWithSaveChangesWillWork()
works.
Don't forget to set up the connectionString in the app.config of the HotelManager.Data.Test project (The EF 'll take care to build the entire DB structure using the mappings contained into the data-layer).
Thanks in advance.
Upvotes: 0
Views: 805