Hibernate persisting incorrect values - postgresql

I have some Hibernate code running against a Postgres 9.5 DB, which looks like roughly like below (anonymized) -
Integer myEntityId = myEntity.getId();
getCurrentSession().evict(myEntity);
myEntity.setId(null);
MyEntity clonedMyEntity = (MyEntity)getCurrentSession().merge(myEntity);
myEntity.setMyBooleanField(false);
getCurrentSession().save(myEntity);
I have an entity myEntity with a large number of fields. I want to create a duplicate of the record with only 1 field value changed. To achieve this, I evict the entity from session, set Primary Key to null, merge it back to session, set the field I want to change, and then save the entity to DB. However, this code (which was working correctly for some time), is not working now. It sees incorrect value for the boolean field I am trying to modify - as a result violating some database constraints. Please help me fix this or suggest a better way to achieve what I am trying.

The error was happening not on adding this record but on add of another record to an audit table, triggered by the addition of this record. A coworker suggested me to use Eclipse Breakpoint view and use the add breakpoint option there and select the ConstraintViolationException class - this helped me to see the error for which trigger was failing and why and accordingly modify the data to suit the database constraint.

Related

Entity Framework 6 - Always update properties that were manually setted by code - Change behavior of change tracker in proxy classes

This is Entity Framework 6.1.3 with .NET v4.0 and SQL Server 2008 R2.
In my, DB I have hundreds of tables with column LastChangedByUser in which I store the login of the user who last updated the row.
Unfortually, I have legacy triggers FOR UPDATE on almost all tables, and they all verify IF UPDATE(LastChangedByUser) and raise an error if this column is not included in the SET clause of the updated. I suppose the original developers did this to make sure the developers included every required column in their manually-written update queries.
By default EF only includes the properties that had their values changed when generating the SET clause of an UPDATE query. And this is causing problems in the following scenario: If previously some row was last changed by "user1", and the same "user1" tries to updates this row again later, EF is not including the LastChangedByUser column in it's generated SET clause, since it was set to the same value that it previously had. And the trigger is raising the error.
My legacy system (pre-EF) includes the LastChangedByUser in the SET clause in manually-written queries, regardless of the value being unaltered, so the trigger validations do OK for those old queries.
So I need to "mimic" this behavior in Entity Framework: if the code explicitly set a property value of a bound Entity proxy, I need its corresponding DbPropertyEntry to have the IsModified set to true regardless of the value being the same as the previous value.
I don't want to include all the columns in the SET cause (I tried this and had other trigger problems). I just want to include the columns that were set explicitly, like:
//this should make the property IsModified become true
//even if it was already "user1" when the entity loaded
myEntity.LastChangedByUser = "user1";
If the code simply dos not change the property (the setter is never called), then the property should remain with IsModified == false.
Is it possible to solve this? Maybe this default behaviour is too intrinsic and can't be changed...
Unfortunately I cannot just disable/drop the triggers, since they do tons of business rules on which the legacy system is dependent. And they are hundreds, so editing each one of them will be really tough...
Thank you!

EF code-first migration: SqlCeException altering NTEXT column

My application uses Entity Framework 5.0 code-first on top of a Sql CE database. Until now, we have used Automatic Migrations to manage entity mapping changes. However, I now have a change for which I need to create a custom migration to ensure no data is lost during the update. I made my changes to the entities, and used the Add-Migration command which generated Up() and Down() methods for me. I customized the Up() method to insert my custom sql to preserve the data, and tested my application.
When I run the application, I received the error:
Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
Ok, I don't understand this because all of my changes are detailed in the Up() method that got executed.
So I turn Automatic Migrations back on just to see what happens. Now I receive this error:
"Cannot alter column of type NTEXT or IMAGE [ Column Name = LastName ]"
This error comes from a table/entity that hasn't even been touched with my changes. The existing database has this string mapped to nvarchar(4000). If I examine the DB after I receive this exception, I observe that the columns have been changed to ntext. What is EF doing? Why is it touching tables that haven't been changed? How can I get more information on what is going on here?
Update:
As a workaround, I attempted to mark each and every string type in my entities with a data annotation as such:
[Column(TypeName = "ntext")]
public virtual string LastName
{
get;
set;
}
Now all of my strings are using ntext in the database. This leads to further exceptions when queries are performed:
The ntext and image data types cannot be used in WHERE, HAVING, GROUP BY, ON, or IN clauses, except when these data types are used with the LIKE or IS NULL predicates.
So, to summarize:
Turning off automatic migrations causes EF to detect phantom changes and throw exceptions
Turning on automatic migration in conjunction with a custom migration causes all existing strings to be mapped to ntext
strings mapped to ntext cannot be queried, effectively making them useless in my application
For me, a modification of an Up method worked out.
SerialNumber = c.String(maxLength: 99)
was applied instead of
SerialNumber = c.String()
i had the same issue and i fixed by editing the table column data type manually by opening SQl Server Compact/SQlite Toolbox explorer windows, and then expend the database name, then expend the table you want to edit and right click the column you want to edit, and click drop script, then run the scrip and the column will be dropped from the table, then right click the table and click add column and from here you can choose what data type you want and add the new column that way. I hope this helps some one.

Entity Framework 5 SaveChanges Not Working, No Error

None of the many questions on this topic seem to match my situation. I have a large data model. In certain cases, only a few of the fields need be displayed on the UI, so for those I replaced the LINQ to Entity query that pulls in everything with an Entity SQL query retrieving only the columns needed, using a Type constructor so that I got an entity returned and not a DbDataRecord, like this:
SELECT VALUE MyModelNameSpace.INCIDENT(incident.FieldA, incident.FieldB, ...) FROM ... AS ...
This works and displays the fields in the UI. And if I make a change, the change makes it back to the entity model when I tab out of the UI element. But when I do a SaveChanges, the changes do not get persisted to the database. No errors show up in the Log. Now if I very carefully replace the above query with an Entity Sql query that retrieves the entire entity, like this:
SELECT VALUE incident FROM MyDB.INCIDENTs AS incident...
Changes do get persisted in the database! So as a test, I created another query like the first that named every column in the entity, which should be the exact equivalent of the second Entity SQL query. Yet it did not persist changes to the database either.
I've tried setting the MergeOption on the returned result to PreserveChanges, to start tracking, like this:
incidents.MergeOption = MergeOption.PreserveChanges;
But that has no effect. But really, if retrieving the entire entity with Entity Sql persists changes, what logical purpose would there be for behaving differently when a subset of the fields are retrieved? I'm wondering if this is a bug?
Gert was correct, the problem was that the entity was not attached. Dank U wel, Gert! Ik was ervan verbluft!
I just wanted to add a little detail to show the full solution. Basically, the ObjectContext has an Attach method, so you'd think that would be it. However, when your Entity SQL select statement names columns, and you create the object using a Type as I did, the EntityKey is not created, and ObjectContext.Attach fails. After trying and failing to insert the EntityKey I created myself, I stumbled across ObjectSet.Attach, added in Entity Framework 4. Instead of failing, it creates the EntityKey if it is missing. Nice touch.
The code was (this can probably be done in fewer steps, but I know this works):
var QueryString = "SELECT VALUE RunTimeUIDesigner.INCIDENT (incident.INCIDENT_NBR,incident.LOCATION,etc"
ObjectQuery<INCIDENT> incidents = orbcadDB.CreateQuery<INCIDENT>(QueryString);
incidents.MergeOption = MergeOption.PreserveChanges;
List<INCIDENT> retrievedIncidents = incidents.ToList<INCIDENT>();
orbcadDB.INCIDENTs.Attach(retrievedIncidents[0]);
iNCIDENTsViewSource.Source = retrievedIncidents;

Cannot insert NULL into a non-identity column in Entity Framework. Funny thing... it's not null?

I have a SalesOrder table with columns for ID and OrderID. ID is an auto-generated int. OrderID is a non-nullable string with a max length of 20, and we use it to store the customer's order number for reference.
After adding my new SalesOrder and calling SaveChanges, I get the following error:
Cannot insert the value NULL into column 'OrderID', table 'SalesOrder'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Problem is, the object that I'm saving actually does have an OrderID! It's almost like it's trying to save the entity first before it saves all the values. Is this how EF handles things?
My setup is EF4.1, using an EDMX model-first approach. StoreGeneratedPattern is set to None. Default Value is currently set to (None) but I've tried various values. Entity Key is False, since it's not part of the key. I've also tried deleting the SalesOrder entity and regenerating it from the database.
I would also like to see your code...I had similar problems when filling objects in a loop then saving them with savechanges. I thought all the fields were populated, but they were not.
I'd have to see your code that executes before the save changes before I can offer anything really helpful.
If your problem is like mine and you are calling savechanges after using an iterator to populate your objects, then you can find the bad data by moving savechanges into the iterator so that it is called with each iteration...but this is all hypothetical guesswork without seeing your code...

Entity Framework SET IDENTITY_INSERT

Is there a way to force the ID value for a new entity in EF when we have an auto-incrementing ID column, i.e. use SET IDENTITY_INSERT behaviour through EF?
Our requirement is that our create form must always show a new, unique ID for the object we're creating on the empty form before it is filled in or saved. The idea is that this ID can be out read to someone over the phone and then the user can complete and save the form after the call is complete. We could reserve an ID by inserting an empty row into the database there and then, but we have unique columns and FKs; instead I've made a 'next ID' table that we increment with locks for safety, and I test this against the top ID in the object table too to be careful. The idea was to then force the use of this new ID when we write back the entity - but I can't see how to get EF to do it.
Is that possible - is it just something I've missed? I don't think the ID even makes it down to the insert so I don't think manually calling SET IDENTITY_INSERT around the SaveChanges would help.
Or do I have to do something else? I can see alternatives:
Change our ID column to not be an identity and take manual control of it all: there's a table ID inheritance here so this is potentially tricky too.
Separate DB ID and user-visible ID into a separate column, and record our unique ID there.
Empty row to reserve the ID, as above; might need some nullability changes, and amending our data read code to ignore these records.
Thanks! This is EF4 (using an EDMX and generated classes not POCOs), and against SQL Server 2008 in case that matters.
Why not use a Guid as primary key. Nothing to do with auto-increment, no concurrency pitfalls etc. You just create the Guid at the moment you create the form. Hand it over to a caller and fill in the form afterwards. When the form is cancelled, no problem. When the form is finished create the entity with the created Guid set the other values of the entity object, apply it to the (a) context and SaveChanges()...
Alternatives that wont alter your schema
Use EF Transaction
You can call context.SaveChanges() and get the autoincremented primary key. Once the process is completed you can commit the transaction. If the transaction is cancelled or there is an error/exception, you can always rollback so you wont have holes/dirty-data in your rows. I suggest you use the singleton pattern and pass the same transaction/context to whatever methods or screens to complete the process.
Just add an additional status: Draft
Save empty form as draft with saved ID, then proceed to edit the form with the information. Once complete save the form as final/ready. If you wont proceed to save the form, you can always recycle the draft.