DbContextScope
DbContextScope copied to clipboard
Please help : Inserted item ID not populated
Hi,
Recently I found your DbContextScope, and I find project very interesting. I wanted to test it but I encounter some issue.
Explanation :
BUSINESS LAYER: "ClientManager"
public int Insert(Client client)
{
using (var context = _dbContextScopeFactory.Create())
{
CLIENT object = ClientMapper.Instance.Map(client);
object = _clientRepository.Add(object);
context.SaveChanges();
client.IdClient = objet.ID_CLIENT;
return object.ID_CLIENT;
}
}
"AddressManager"
public int Insert(Address address)
{
using (var context = _dbContextScopeFactory.Create())
{
ADDRESS object = AddressMapper.Instance.Map(address);
_addressRepository.Add(object);
context.SaveChanges();
return object.ID_ADRESSE;
}
}
I have my console program for test and it's works fine.
But now if I want to add to "ClientManager" another function:
public int InsertClientWithAddress(Client client, Adresse address)
{
using (var context = _dbContextScopeFactory.Create())
{
int id = Insert(client)
address.IdClient = id; // = 0 because no SaveChanges
_addressManager.Insert(address);
context.SaveChanges();
return client.IdClient;
}
}
It's not working because my client ID is auto-increment integer in database and it's not initialized because of DbContextScope.SaveChanges
How I can resolve this issue with your framework?
Thanks you in advance
P.S
Sorry for my English :)
Your title needs some work; I assume the actual issue is "Inserted item ID not populated"?
You may need to move the last two lines out of the using block; closing the connection to the database should complete the transaction. Otherwise, Context.Entry(address).Reload() might work.
Sorry, but It doesn't working... When I use a classic TransactionScope with entity-framework it's works very well because when I call context.SaveChanges() => Id property is populated correctly and at the and I call Commit.
But in this case with DbContextScope SaveChages() Do anything when the are parent scope.
Finally, I try this to replace DbContextScope with TransactionScope and it's seems to work but I don't know if it's correct approach ?
public int InsertClientWithAddress(Client client, Adresse address)
{
using (TransactionScope scope = new TransactionScope())
{
int id = Insert(client)
address.IdClient = id; // =now it's OK
_addressManager.Insert(address);
scope.Complete();
return id;
}
}
You can overcome this issue by calling SaveChanges from the DbContext (not the DbContextScope) in your implementation of _clientRepository.Add