How to get EF Code First DbContext Transaction row identity? - entity-framework

Is it possible to get the identity of a record after the SaveChanges method but prior to the TransactionScope.Complete call using the DbContext? Do we need to cast to ObjectContext to get this functionality?
We need this when we send a message to a transactional queue on a separate server using MSDTC.
Example:
static void Main(string[] args)
{
const string qName = ".\\Private$\\DbContextTransactions";
var db = new BlogDb();
// force db creation & create queue
Console.WriteLine("Count={0}", db.Posts.Count());
if (!MessageQueue.Exists(qName))
MessageQueue.Create(qName, true); // transactional
try
{
using (var t = new TransactionScope())
using (MessageQueue q = new MessageQueue(qName))
{
var post = new Post() { Title = "Test " + DateTime.Now.Ticks.ToString() };
db.Posts.Add(post);
db.SaveChanges();
// TODO: how do we get post.Id (updated identity)?
q.Send(post.Id, MessageQueueTransactionType.Automatic);
t.Complete();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine("Count={0}", db.Posts.Count());
Console.ReadLine();
}

The identity value should always be set after you call SaveChanges, even inside a TransactionScope.

Related

Revert DbContext.Savechanges in case a second DbContext.Savechanges fail

I have the following code, which stores information in two different tables in the same method
public static async Task<Response> AddStockTransaction(StockTransactionsHeader header, List<StockTransactionsDetails> details)
{
using (DataContext dbContext = new DataContext())
{
try
{
dbContext.StockTransactionsHeader.Add(header);
await dbContext.SaveChangesAsync();
int hearderID = header.TransactionHeaderID;
foreach (var item in details)
{
item.TransactionHeaderID = hearderID;
}
dbContext.StockTransactionsDetails.AddRange(details);
await dbContext.SaveChangesAsync();
return new Response
{
IsSuccess = true
};
}
catch (Exception ex)
{
return new Response
{
IsSuccess = false,
Message = ex.Message
};
}
}
}
How can I do, in case there is an exception in the second SaveChanges () to revert the first one?
Once SaveChanges has been called, your datat is stored on your database. You should not call SaveChanges more than once in a call, unless you are willingly to persist the intermediate steps.
You can use a transaction scope to create managed transactions :
using (TransactionScope scope = CreateTransactionScope())
{
DoSomthing(context);
scope.Complete();
}
however, if the failure of the second part involves rolling back the first one, this means that both parts belong to the same transaction, therefore simply omitting the first SaveChanges would turn your code into a single transaction.
From my another awnser: You could use DbTransaction class.
private void TestTransaction()
{
var context = new MyContext(connectionString);
using (var transaction = context.Database.BeginTransaction())
{
try
{
// do your stuff
// commit changes
transaction.Commit();
}
catch
{
// 'undo' all changes
transaction.Rollback();
}
}
}

No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call, Exception

Have a list of data need to be saved. Before the save had to delete the existing data and save the new data.
If any of the delete & save is failed that transaction need to roll back, rest of the delete & save transaction should continue.
public LabResResponse saveLabResult(List<LabResInvstResultDto> invstResults) {
LabResResponse labResResponse = new LabResResponse();
List<Long> relInvstid = new ArrayList<Long>();
try{
if(invstResults != null){
List<LabResInvstResult> labResInvstResults = mapper.mapAsList(invstResults, LabResInvstResult.class);
for(LabResInvstResult dto: labResInvstResults){
if(dto != null){
//delete all child records before save.
deleteResult(dto, relInvstid);
}
}
}
labResResponse.setRelInvstids(relInvstid);
}catch(Exception e){
e.printStackTrace();
}
return labResResponse;
}
Here new transaction will added for each delete & save
#Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = { Exception.class })
private void deleteResult(LabResInvstResult dto, List<Long> relInvstid) {
try{
labResultRepo.deleteById(dto.getId());
LabResInvstResult result = labResultRepo.save(dto);
}catch(Exception e){
e.printStackTrace();
}
}
On delete it throws an exception "Caused by: javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call"
I can solve this by adding a #Transactional for public LabResResponse saveLabResult(List invstResults) method.
But my intial usecase will not work this will roll back entire list of transaction.
Here are two problems.
The first problem is that you call the "real" deleteResult method of the class. When Spring sees #Transactional it creates a proxy object with transactional behavior. Unless you're using AspectJ it won't change the class itself but create a new one, proxy. So when you autowire this bean you will be able use proxy's method that runs transaction related logic. But in your case you're referencing to the method of the class, not proxy.
The second problem is that Spring (again if AspectJ is not used) can't proxy non-public methods.
Summary: make the deleteResult method public somehow and use proxied one. As a suggestion, use another component with deleteResult there.
You are catching exception out of for loop, while your requirement says you want to continue the loop for other objects in list.
Put your try/catch block with-in loop. It should work fine
public LabResResponse saveLabResult(List<LabResInvstResultDto> invstResults) {
LabResResponse labResResponse = new LabResResponse();
List<Long> relInvstid = new ArrayList<Long>();
try{
if(invstResults != null){
List<LabResInvstResult> labResInvstResults = mapper.mapAsList(invstResults, LabResInvstResult.class);
for(LabResInvstResult dto: labResInvstResults){
if(dto != null){
//delete all child records before save.
try {
deleteResult(dto, relInvstid);
} catch(Exception e){
e.printStackTrace();
}
}
}
}
labResResponse.setRelInvstids(relInvstid);
}catch(Exception e){
e.printStackTrace();
}
return labResResponse;
}

org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessions

I am working rest services with spring and hibernate,for updating employee data using below code, but when run I got below error
{
"code": 0,
"message": "org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessions"
}
DataDaoImpl.java
#Override
public Employee getEntityById(long id) throws Exception {
session = sessionFactory.openSession();
Employee employee = (Employee) session.load(Employee.class,
new Long(id));
tx = session.getTransaction();
session.beginTransaction();
tx.commit();
return employee;
}
RestController.jav
#RequestMapping(value = "/save/{id}", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
Status saveUser(#PathVariable("id") long id,#RequestBody Employee employee) {
Employee employeeupdate = null;
try {
employeeupdate = dataServices.getEntityById(id);
employeeupdate.setFirstName(employee.getFirstName());
employeeupdate.setLastName(employee.getLastName());
employeeupdate.setEmail(employee.getEmail());
employeeupdate.setPhone(employee.getPhone());
dataServices.updateEntity(employeeupdate);
return new Status(1, "Employee updated Successfully !");
} catch (Exception e) {
// e.printStackTrace();
return new Status(0, e.toString());
}
}
#Override
public boolean updateEntity(Employee employeeupdate) throws Exception {
session = sessionFactory.openSession();
tx = session.beginTransaction();
session.update(employeeupdate);
tx.commit();
session.close();
return false;
}
What mistake have I done here?
In the getEntityById(...) method the session is not closed. Close the session using session.close(); before returning the employee and try.
Don't open 2 sessions. Open just one and use it.
place the
session = sessionFactory.openSession();
tx = session.beginTransaction();
In the beginning of saveUser() and pass the session/transaction to the methods. Actually you don't need transaction in the getEntityById() - you change nothing.
Appart of #StanislavL answer, there are some errors in your code getEntityById() should be (you need close a session and place a transaction above load()).
#Override
public Employee getEntityById(long id) throws Exception {
session = sessionFactory.openSession();
tx = session.getTransaction();
session.beginTransaction();
Employee employee = (Employee) session.load(Employee.class,
new Long(id));
tx.commit();
session.close();
return employee;
}
But this variant is not very correct too, you should catch an exception use a finally block and rollback a transaction. The best way is using this pattern doInTransaction().
Update
It is better to get an entity this way
Employee employee = (Employee) session.get(Employee.class, id);
In short, you should not create session in your DAO.
Given that you are using Spring, you should avoid manually creating the Session/Transaction. Please make use of Spring to manage the transaction and session creation, by relying on Spring's transaction control and things like LocalEntityManagerFactoryBean

Unstable application uses SqlDependency. Several states and errors

I have a windows application using SqlDependency running at separated thread pool, this application represents a log monitor UI get the latest rows added in a specific table in the database and view it in a DataGridView. You can see the application source code from this LINK, or follow this script.
const string tableName = "OutgoingLog";
const string statusMessage = "{0} changes have occurred.";
int changeCount = 0;
private static DataSet dataToWatch = null;
private static SqlConnection connection = null;
private static SqlCommand command = null;
public frmMain()
{
InitializeComponent();
}
private bool CanRequestNotifications()
{
// In order to use the callback feature of the
// SqlDependency, the application must have
// the SqlClientPermission permission.
try
{
SqlClientPermission perm = new SqlClientPermission(PermissionState.Unrestricted);
perm.Demand();
return true;
}
catch
{
return false;
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
// This event will occur on a thread pool thread.
// Updating the UI from a worker thread is not permitted.
// The following code checks to see if it is safe to
// update the UI.
ISynchronizeInvoke i = (ISynchronizeInvoke)this;
// If InvokeRequired returns True, the code
// is executing on a worker thread.
if (i.InvokeRequired)
{
// Create a delegate to perform the thread switch.
OnChangeEventHandler tempDelegate = new OnChangeEventHandler(dependency_OnChange);
object[] args = { sender, e };
// Marshal the data from the worker thread
// to the UI thread.
i.BeginInvoke(tempDelegate, args);
return;
}
// Remove the handler, since it is only good
// for a single notification.
SqlDependency dependency = (SqlDependency)sender;
dependency.OnChange -= dependency_OnChange;
// At this point, the code is executing on the
// UI thread, so it is safe to update the UI.
++changeCount;
lblChanges.Text = String.Format(statusMessage, changeCount);
// Reload the dataset that is bound to the grid.
GetData();
}
AutoResetEvent running = new AutoResetEvent(true);
private void GetData()
{
// Start the retrieval of data on another thread to let the UI thread free
ThreadPool.QueueUserWorkItem(o =>
{
running.WaitOne();
// Empty the dataset so that there is only
// one batch of data displayed.
dataToWatch.Clear();
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
// Create and bind the SqlDependency object
// to the command object.
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
adapter.Fill(dataToWatch, tableName);
try
{
running.Set();
}
finally
{
// Update the UI
dgv.Invoke(new Action(() =>
{
dgv.DataSource = dataToWatch;
dgv.DataMember = tableName;
//dgv.FirstDisplayedScrollingRowIndex = dgv.Rows.Count - 1;
}));
}
}
});
}
private void btnAction_Click(object sender, EventArgs e)
{
changeCount = 0;
lblChanges.Text = String.Format(statusMessage, changeCount);
// Remove any existing dependency connection, then create a new one.
SqlDependency.Stop("Server=.; Database=SMS_Tank_Log;UID=sa;PWD=hana;MultipleActiveResultSets=True");
SqlDependency.Start("Server=.; Database=SMS_Tank_Log;UID=sa;PWD=hana;MultipleActiveResultSets=True");
if (connection == null)
{
connection = new SqlConnection("Server=.; Database=SMS_Tank_Log;UID=sa;PWD=hana;MultipleActiveResultSets=True");
}
if (command == null)
{
command = new SqlCommand("select * from OutgoingLog", connection);
//SqlParameter prm =
// new SqlParameter("#Quantity", SqlDbType.Int);
//prm.Direction = ParameterDirection.Input;
//prm.DbType = DbType.Int32;
//prm.Value = 100;
//command.Parameters.Add(prm);
}
if (dataToWatch == null)
{
dataToWatch = new DataSet();
}
GetData();
}
private void frmMain_Load(object sender, EventArgs e)
{
btnAction.Enabled = CanRequestNotifications();
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
SqlDependency.Stop("Server=.; Database=SMS_Tank_Log;UID=sa;PWD=hana;MultipleActiveResultSets=True");
}
The problem:
I have many situations of errors, (images in the first comment)
(No. 1):
I got this error dialog, and I don't know its reason.
(No. 2):
I got nothing in my grid view (No errors, and no data).
(No. 3):
I got only columns names and no rows, although the table has rows.
I need help please.
I may be wrong but a DataSet does not seem to have notification capability so the DataGridView may be surprised if you change it behind its back.
You could try to explicitly show your're changing the data source by first setting it to null:
dgv.DataSource = null;
dgv.DataSource = dataToWatch;
dgv.DataMember = tableName;
It's worth a try...

Can I dispose a DataTable and still use its data later?

Noob ADO.NET question: Can I do the following?
Retrieve a DataTable somehow.
Dispose it.
Still use its data. (But not send it back to the database, or request the database to update it.)
I have the following function, which is indirectly called by every WebMethod in a Web Service of mine:
public static DataTable GetDataTable(string cmdText, SqlParameter[] parameters)
{
// Read the connection string from the web.config file.
Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/WSProveedores");
ConnectionStringSettings connectionString = configuration.ConnectionStrings.ConnectionStrings["..."];
SqlConnection connection = null;
SqlCommand command = null;
SqlParameterCollection parameterCollection = null;
SqlDataAdapter dataAdapter = null;
DataTable dataTable = null;
try
{
// Open a connection to the database.
connection = new SqlConnection(connectionString.ConnectionString);
connection.Open();
// Specify the stored procedure call and its parameters.
command = new SqlCommand(cmdText, connection);
command.CommandType = CommandType.StoredProcedure;
parameterCollection = command.Parameters;
foreach (SqlParameter parameter in parameters)
parameterCollection.Add(parameter);
// Execute the stored procedure and retrieve the results in a table.
dataAdapter = new SqlDataAdapter(command);
dataTable = new DataTable();
dataAdapter.Fill(dataTable);
}
finally
{
if (connection != null)
{
if (command != null)
{
if (dataAdapter != null)
{
// Here the DataTable gets disposed.
if (dataTable != null)
dataTable.Dispose();
dataAdapter.Dispose();
}
parameterCollection.Clear();
command.Dispose();
}
if (connection.State != ConnectionState.Closed)
connection.Close();
connection.Dispose();
}
}
// However, I still return the DataTable
// as if nothing had happened.
return dataTable;
}
The general rule is to Dispose anything that implements IDisposable, whether it "needs it" or not. Saves you from the times when it "needs it" and you didn't think to Dispose.
Once you've called Dispose on an object, you shouldn't use it anymore. Period. It violates the entire concept of Dispose.
This is why you shouldn't call Dispose on an object that you are returning from a method. Leave it up to the caller to call Dispose when they're done with the object.
BTW, your code could be simpler. More like this:
using (SqlConnection connection = new SqlConnection(connectionString.ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(cmdText, connection))
{
//...
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
return dataTable;
}
}
}
Well, you can't have your cake and eat it :)
Close the connection and so on, sure, but why do you need to dispose the table? That's not necessary. Just return it as-is.
Otherwise you'd be in a position where you... copy the table to something else and then return that instead? If you were using a ORM for example and mapping data to objects and then returning the objects this would make sense, but if you're not then just use the table/dataset directly.