Using Session.Flush then ITransaction.Commit makes data rollback - sql-server

I'm trying to update an entity using Session.Update then continue to execute another SQL query. The other query did not see the changed value. When i traced it using profiler, Session.Update did nothing.
public class InvoiceService()
{
public void Update(Invoice invoice)
{
using (var trans = BeginTransaction())
{
Session.Update(invoice); //Nhibernate did not update invoice.
ExecuteNamedQuery(); //Query executed before invoice updated.
trans.Commit(); //Invoice updated.
}
}
}
Then i add Session.Flush after Session.Update.
using (var trans = BeginTransaction())
{
Session.Update(invoice);
Session.Flush()
ExecuteNamedQuery();
trans.Commit();
}
After Session.Flush executed, SQL query for update is executed also.
It works perfectly. The execution order is correct. But then i executed another method to get all invoices. Committing transaction makes nhibernate execute update query to update my updated invoice earlier with old values. (ex: Quantity = 20, updated to 10, then updated again to 20)
public void FindAll()
{
using (var trans = BeginTransaction())
{
var invoices = Session.CreateCriteria<Invoice>().List<Invoice>();
trans.Commit(); // In here invoice that i updated earlier get updated again, using old values.
return invoices;
}
}
Why it's getting updated again?
What's the solution for this problem?
Thanks in advance.

Update is an unfortunate name for the method; the purpose of Update is to attach a transient instance to a new session. See the documentation for update and make sure you understand instance states.
The invoice is updated to the original values because NHibernate thinks it has changed. This "phantom" update may be caused by a property changing unexpectedly. A typical root cause is a nullable database column mapped to a non-nullable property (or vice-versa). The easiest way to troubleshoot is to turn on dynamic-update in the session factory configuration so that you can see which properties NHibernate detects as dirty.

Related

Update records using EntityFrameworkCore

I'm new to using EF to handle data in SQL. In a MVC Core project we're testing EF (Microsoft.EntityFrameworkCore, version 2.2.3) to handle data.
When trying to update data and update failed for some reason (missing fields etc) it seemed like EF actually deleted the record from the database (MSSQL 2014) instead of throwing an update error...
Is it possible?
Code for updating:
public void Update(Contact contact)
{
_dbContext.Update(contact);
_dbContext.SaveChanges();
}
When trying to update data and update failed for some reason (missing fields etc) it seemed like EF actually deleted the record from the database (MSSQL 2014) instead of throwing an update error...
Is it possible?
It should not.
test it, try to debug here
_dbContext.Update(contact);
_dbContext.SaveChanges();
var updated = _dbContext.Contacts.FirstOrDefault(x => x.Id == contact.Id); //debug here
check if it has a value, if still none, these are the scenarios i can think of that may have caused your problem
investigate the missing field specially if it is not nullable.
is the _dbContext used here is the same connection string used with everything?
is the [Key] attribute listed on your Contact entity?
public class Contact
{
[Key]
public int Id
}
overridden the SaveChanges function?
is what you are passing Contact contains a Key and it is not 0?
is a delete function called after Update?
try using SQL Profiler to look at the Linq to SQL if it really generated an update query and if it is really pointing at the right [Key]
but if it is still not working properly, you could do
public void Update(Contact contact)
{
var selectedContactToBeUpdated = _dbContext.Contacts.FirstOrDefault(x => x.Id == contact.Id);
if (selectedContactToBeUpdated != null)
{
selectedContactToBeUpdated.PropertyToBeUpdated1 = newValue;
selectedContactToBeUpdated.PropertyToBeUpdated2 = newValue2;
//additional Properties
_dbContext.SaveChanges();
}
}
in the scenario above, it will only generate an Update statement with fields you have changed.

Error in saving related objects in Entity Framework

I have a structure like this
DRDLines:
ID
DrawingRevisionID
DrawingRevision:
ID
Name
They're related in a one-to-many relationship.
In this code example
DRDLine line;
using (var db = new AMPX_DCEntities())
{
line = db.DRDLines.Single(p => p.ID == 1);
System.Console.WriteLine(line.DrawingRevision.ID);
}
using (var db = new AMPX_DCEntities())
{
var id = 12;
line.DrawingRevisionID = id;
}
using (var db = new AMPX_DCEntities())
{
db.Entry(line).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
I get this error
A referential integrity constraint violation occurred: The property value(s) of 'DrawingRevision.ID' on one end of a relationship do not match the property value(s) of 'DRDLine.DrawingRevisionID' on the other end.
What I've found: it doesn't update relations in DRDLines inside DrawingRevision
Debugging I see:
line.DrawingRevision.DRDLines[0].ID != line.DrawingRevisionID
If I remove line
System.Console.WriteLine(line.DrawingRevision.ID);
or write it like this
System.Console.WriteLine(line.DrawingRevisionID);
everything goes without errors. But I need that line to be used.
So, how can I fix that?
My guess is that the problem is caused by repeatedly creating a new context and then disposing it. When you set the DrawingRevisionID here
using (var db = new AMPX_DCEntities())
{
var id = 12;
line.DrawingRevisionID = id;
}
line is detached from the dbcontext from which it was retreived, but isn't attached to the new DbContext you've created, hence EF won't wire up the relationships when you change the ID.
You could attach the line object back to the context before changing the ID
db.DRDLines.Attach(line);
That will change both the IDs (although you could just change the other ID manually). Since that context is then disposed, you may need to set the EntityState to Modified for the DrawingRevision (or at least of the ID property) in the last DbContext session.
Also, I would add an Include to the original query to eagerly load the DrawingRevision. At the moment its only loaded when you query the ID on the System.Console line, hence why the behaviour is different. This also causes an extra trip to the database. Putting it into an include will be more efficient and more predictable.

Get list of modified objects after Entity Framework Update

So I'm trying to prevent a race condition between applications.
Using IsolationLevel/TransactionScope, I can lock the table the way I need to, but need to run the update operation first, then operate on the list of modified objects.
To do this, I need to run the update and get the list of updated ID's all in one shot.
If I were to try to take the IDs first, that wouldn't lock the table, and another app instance could query for that same list, before they were flagged.
Is there a way to do something like:
//modify some objects
var updatedIds = context.SaveChanges();
//Process updatedIds
Is there a way to do this? I've tried looking through the ObjectContext entries, but after the Save there doesn't seem to be anything.
Maybe I'll have to do an sproc?
This code can go into your Context class and should give you what you need
public override int SaveChanges()
{
using (var scope = new System.Transactions.TransactionScope())
{
//pre processing
var result = base.SaveChanges();
//post processing
scope.Complete();
return result;
}
}

Insert Entity into EntityCollection w/ RIA

I've got a one-to-many relationship set up. (Ex. A Person with many Phone Numbers). In my get query i have this.ObjectContext.Person.Include("PhoneNumbers") and the in generated MetaData including public EntityCollection<PhoneNumbers> PhoneNumbers{ get; set; } I have also set up a DTO with this and other properties i need.
[Include]
[Association("Name","thisKey","otherKey")]
public IEnumerable<PhoneNumbers> PNums { get; set; }
I can retrieve all the data alright, and display it in silverlight, but when I create a new one I run into problems. I've got this kind of thing going on:
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
if (dgMMs.SelectedItem != null)
{
PhoneNumbers wb = new PhoneNumbers ();
wb.this = tbThis.Text;
wb.that = tbThat.Text;
wb.other = tbOther.Text;
wb.whatnot = tbwhatnot.Text;
((Person)dgMMs.SelectedItem).PNums.Add(wb);
}
}
Then I get this error when calling TDataSource.SubmitChanges();:
Message = "Submit operation failed
validation. Please inspect
Entity.ValidationErrors for each
entity in EntitiesInError for more
information."
Alright, So i did that, and sure enough there is an error, but I don't quite understand why there is. I have a non-nullable field in the database for a last_modified_by field which i didn't set when I created it and added it to the entityCollection, and I guess this would be causing it, but my question comes from why RIA doesn't call my Insert method in my service that I've created because I want to set that field there. Like so:
public void InsertPhoneNumber(PhoneNumbers pnum)
{
pnum.last_modified = DateTime.Today;
pnum.last_modified_by = Thread.CurrentPrincipal.Identity.Name;
if ((pnum.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(pnum, EntityState.Added);
}
else
{
this.ObjectContext.PhoneNumbers.AddObject(pnum);
}
}
But it's like RIA adds my object and calls it own Insert Method. So I rolled with it at first, and just set the property up in the UI, then it would give me this error:
Message = "Submit operation failed. An
error occurred while updating the
entries. See the inner exception for
details. Inner exception message:
Cannot insert explicit value for
identity column in table
'iset_trkr_writeback' when
IDENTITY_INSERT is set to OFF."
I never set the identity field to anything, I thought RIA would do this for me. But when i debug and take a look, it has a 0 for the value. But at least this time it calls my insert method in my service... Maybe I'm missing a big something for my process, but I really could use some help. Thanks:)
You using Entity Framework? If so, you need a [Key] attribute on at least one field in your metadata. Or create an identity/PK column (int/guid), and then update the metadata.

Need advice on complex insert scenario using LinqToSql with repository pattern

I have a User table and a ClubMember table in my database. There is a one-to-one mapping between users and club members, so every time I insert a ClubMember, I need to insert a User first. This is implemented with a foreign key on ClubMember (UserId REFERENCES User (Id)).
Over in my ASP.NET MVC app, I'm using LinqToSql and the Repository Pattern to handle my persistence logic. The way I currently have this implemented, my User and ClubMember transactions are handled by separate repository classes, each of which uses its own DataContext instance.
This works fine if there are no database errors, but I'm concerned that I'll be left with orphaned User records if any ClubMember insertions fail.
To solve this, I'm considering switching to a single DataContext, which I could load up with both inserts then call DataContext.SubmitChanges() only once. The problem with this, however, is that the Id for User is not assigned until the User is inserted into the database, and I can't insert a ClubMember until I know the UserId.
Questions:
Is it possible to insert the User into the database, obtain the Id, then insert the ClubMember, all as a single transaction (which can be rolled back if anything goes wrong with any part of the transaction)? If yes, how?
If not, is my only recourse to manually delete any orphaned User records that get created? Or is there a better way?
You can use System.Transactions.TransactionScope to perform this all in an atomic transaction, but if you are using different DataContext instances, it will result in a distributed transaction, which is probably not what you really want.
By the sounds of it, you're not really implementing the repository pattern correctly. A repository should not create its own DataContext (or connection object, or anything else) - these dependencies should be passed in via a constructor or public property. If you do this, you'll have no problem sharing the DataContext:
public class UserRepository
{
private MyDataContext context;
public UserRepository(MyDataContext context)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
}
public void Save(User user) { ... }
}
Use the same pattern for ClubMemberRepository (or whatever you call it), and this becomes trivial:
using (MyDataContext context = new MyDataContext())
{
UserRepository userRep = new UserRepository(context);
userRep.Save(user);
ClubMemberRepository memberRep = new ClubMemberRepository(context);
memberRep.Save(member);
context.SubmitChanges();
}
Of course, even this is a little bit iffy. If you have a foreign key in your database, then you shouldn't even need two repositories, because Linq to SQL manages the relationship. The code to create should simply look like this:
using (MyDataContext context = new MyDataContext())
{
User user = new User();
user.Name = "Bob";
user.ClubMember = new ClubMember();
user.ClubMember.Club = "Studio 54";
UserRepository userRep = new UserRepository(context);
userRep.Save(user);
context.SubmitChanges();
}
Don't fiddle with multiple repositories - let Linq to SQL handle the relationship for you, that's what ORMs are for.
Yes, you can do it in a single transaction. Use the TransactionScope object to begin and commit the transaction (and rollback if there is an error of course)

Resources