LINQ to Entities - How best to obtain the IDENTITY value after calling SaveChanges() - linq

There have been numerous questions posed on this site relating to the retrieval of the IDENTITY after an insert is performed. The way we have been getting the identity is to make the call below, immediately after calling SaveChanges();
context.MyClass.OrderByDescending(c => c.Id).FirstOrDefault();
This seems to work consistently may be completely adequate; however, it has the appearence of opening up a potential for error, should another record be added in between the calls. So the first question is, given that EF performs withing a transacional context, is this method sound?
Secondly, the answer provided to the following question suggests there may be a better way.
Linq to SQL - How to find the the value of the IDENTITY column after InsertOnSubmit()
In that answer, after calling SubmitChanges(), the following call (where "tst" represents the user's class) retrieves the value.
Response.Write("id:" + tst.id.ToString)
This appears to work exactly the same way in LINQ to Entities, where after the call to save changes the instance of the class now includes the id.
context.MyClass.Add(myClass);
context.SaveChanges();
int myNewIdentity = myClass.Id;
Since we are asking for the the actual ID of the class instance (actual record) it would appear to be failsafe. And, it seems logical that the designers of EF should make such basic functionality available. Can anyone confirm that this is proper way to get the identity or at least a best practice?

Yes, LINQ-to-Entities (and LINQ-to-SQL for that matter) will set the generated identity column back in the entity for you after SaveChanges is called. It will also do so for any foreign keys that couldn't be set ahead of time (for instance, a new parent row + a new child row are saved together, and after SaveChanges you'll have the right value in the child row's FK value).
Your particular concern is documented in the 'Working with Entity Keys' page:
http://msdn.microsoft.com/en-us/library/dd283139.aspx
The particular section is 'Entity Keys and Added Objects' and the particular steps are:
4 - If the INSERT operation succeeds, server-generated values are written back to the ObjectStateEntry.
5 - The ObjectStateEntry updates the object with the server-generated value.

Related

Entity Framework returns different result with AsNoTracking

I use Entity Framework in combination with an Oracle database. If I create a query like
myLinqStatement.ToListAsync()
I get wrong data returned as a result. If I change the statement to
myLinqStatement.AsNoTracking.ToListAsync()
I get the correct data.
I also checked the native SQL query, which is generated by myLinqStatement.ToListAsync(). The generated SQL query is correct, because I get the correct data.
So is there a problem in the mapping? And why is it working with AsNoTracking?
Thanks!
What AsNoTracking does is to retrieve the data without attaching it to the context, hence any changes you apply over the data do not take effect unless you attach it again so that EF knows it should track its changes.
The code snippets you've provided do not show the whole picture, from the moment a context is created, but is it possible that other parts of your code mutate data before you call myLinqStatement.ToListAsync()?
As you mention that myLinqStatement.AsNoTracking.ToListAsync() returns expected data, makes me assume that there are some side effects in your code that AsNoTracking simply is not aware so just returns whatever it finds in your db
I came across this question because I had a similar issue with Entity Framework Core querying a DB view, the issue was cause because view didn't have a key defined, after defining a key for the entity that map to that DB view, the query returned the same result in both cases (using AsNoTracking or without using it).
In T-SQL a key for a DB view can be defined this way:
CREATE UNIQUE CLUSTERED INDEX UQ_MyDBViewName_ColumnKey
ON dbo.MyDBViewName (ColumnKey);
And in code, you can map the key using the [Key] attribute in the corresponding property of the entity or using the EF fluent API. It will depend of what the project is using.
Either way, using AsNoTracking on a query that goes directly to a DB view makes a lot of sense. Also, if for some reason the query of the view does not allow us to define a key for that view, then the option is to use AsNoTracking.
Hope it helps anyone else having the same issue.

Using Oracle's GUID()-generated ID's in Grails/Hibernate

I trying to use Grails Scaffolding to throw a quick CRUD application together around some legacy database tables. It is an Oracle database, and the primary key value is intended to be populated by Oracle's GUID() function.
Based on this earlier StackOverflow question, I tried specifying "guid" as the Hibernate generator for this column in my Grails domain class:
...
static mapping = {
table name: "OWNER"
version false
columns {
id column: "OWNER_OID", generator: "guid"
name column: "NAME"
...
}
}
...
When I run my Grails app, viewing and even editing records works just fine. However, when I try to create a new record, things blow up with the Oracle error message "ORA-02289: sequence does not exist".
I enabled SQL logging for my datasource, and see Grails/Hibernate trying to execute the following during a save operation:
select hibernate_sequence.nextval from dual
This doesn't look right at all, and doesn't match the generated SQL from that earlier StackOverflow question linked above. Does anyone see something I am missing here, or otherwise know how to make Grails/Hibernate populate a primary key column with Oracle GUID values?
Whew... after another day of wrestling with this, I think I have my arms around the thing. This answer covers a bit more ground than the original question description, but that's because I found yet more problems after getting past the Hibernate generator issue.
Issue #1: Getting an Oracle GUID() value
As covered by Adam Hawkes' answer, the "guid" Hibernate generator is unmaintained and only works for older versions of the Oracle dialect.
However, if you use the Hibernate generator "assigned" (meaning that you want to set primary keys manually rather than have Hibernate auto-generate them), then you can insert values pulled from an Oracle SYS_GUID() call.
Even though Hibernate's newer Oracle dialects don't support "guid" seamlessly, they still understand the SQL necessary to generate these values. If you are inside of a Controller, you can fetch that SQL query with the following:
String guidSQL = grailsApplication.getMainContext().sessionFactory.getDialect().getSelectGUIDString()
If you are inside of a domain class instead, you can still do this... but you will need to first inject a reference to grailsApplication. You probably want to do this in a Controller, though... more on this below.
If you're curious, the actual String returned here (for Oracle) is:
select rawtohex(sys_guid()) from dual
You can execute this SQL and fetch the generated ID value like this:
String guid = grailsApplication.getMainContext().sessionFactory.currentSession.createSQLQuery(guidSQL).list().get(0)
Issue #2: Actually using this value in a Grails domain object
To actually use this GUID value in your Grails domain class, you need to use the Hibernate generator "assigned". As mentioned earlier, this declares that you want to set your own ID's manually, rather than letting Grails/GORM/Hibernate generate them automatically. Compare this modified code snippet to the one in my original question above:
...
static mapping = {
table name: "OWNER"
version false
id column: "OWNER_OID", generator: "assigned"
name column: "NAME"
...
}
...
In my domain class, I changed "guid" to "assigned". I also found that I needed to eliminate the "columns {}" grouping block, and move all my column information up a level (weird).
Now, in whichever Controller is creating these domain objects... generate a GUID as described above, and plug it into the object's "id" field. In a Controller generated automatically by Grails Scaffolding, the function will be "save()":
def save() {
def ownerInstance = new Owner(params)
String guidSQL = grailsApplication.getMainContext().sessionFactory.getDialect().getSelectGUIDString()
ownerInstance.id = grailsApplication.getMainContext().sessionFactory.currentSession.createSQLQuery(guidSQL).list().get(0)
if (!ownerInstance.save(flush: true, insert: true)) {
render(view: "create", model: [ownerInstance: ownerInstance])
return
}
flash.message = message(code: 'default.created.message', args: [message(code: 'owner.label', default: 'Owner'), ownerInstance.id])
redirect(action: "show", id: ownerInstance.id)
}
You might think to try putting this logic directly inside the domain object, in a "beforeInsert()" function. That would definitely be cleaner and more elegant, but there are some known bugs with Grails that prevent ID's from being set in "beforeInsert()" properly. Sadly, you'll have to keep this logic at the Controller level.
Issue #3: Make Grails/GORM/Hibernate store this properly
The plain truth is that Grails is primarily intended for virgin-new applications, and its support for legacy databases is pretty spotty (in fairness, though, it's a bit less spotty than other "dynamic" frameworks I've tried). Even if you use the "assigned" generator, Grails sometimes gets confused when it goes to persist the domain object.
One such problem is that a ".save()" call sometimes tries to do an UPDATE when it should be doing an INSERT. Notice that in the Controller snippet above, I have added "insert: true" as a parameter to the ".save()" call. This tells Grails/GORM/Hibernate explicitly to attempt an INSERT operation rather than an UPDATE one.
All of the stars and planets must be in alignment for this to work right. If your domain class "static mapping {}" block does not set the Hibernate generator to "assigned", and also set "version false", then Grails/GORM/Hibernate will still get confused and try to issue an UPDATE rather than an INSERT.
If you are using auto-generated Grails Scaffolding controllers, then it is safe to use "insert: true" in the Controller's "save()" function, because that function in only called when saving a new object for the first time. When a user edits an existing object, the Controller's "update()" function is used instead. However, if you are doing your own thing in your own custom code somewhere... it will be important to check on whether a domain object is already in the the database before you make a ".save()" call, and only pass the "insert: true" parameter if it really is a first-time insert.
Issue #4: Using natural keys with Grails/GORM/Hibernate
One final note, not having to do with Oracle GUID values, but related to these Grails issues in general. Let's say that in a legacy database (such as the one I've been dealing with), some of your tables use a natural key as their primary key. Say you have an OWNER_TYPE table, containing all the possible "types" of OWNER, and the NAME column is both the human-readable identifier as well as the primary key.
You'll have to do a couple of other things to make this work with Grails Scaffolding. For one thing, the auto-generated Views do not show the ID field on the screen when users are creating new objects. You will have to insert some HTML to the relevant View to add a field for the ID. If you give the field a name of "id", then the auto-generated Controller's "save()" function will receive this value as "params.id".
Secondly, you have to make sure that the auto-generated Controller's "save()" function properly inserts the ID value. When first generated, a "save()" starts off by instantiating a domain object from the CGI parameters passed by the View:
def ownerTypeInstance = new OwnerType.get( params )
However, this does not handle the ID field you added to your View. You will still need to set that manually. If on the View you gave the HTML field a name of "id", then it will be available in "save()" as "params.id":
...
ownerTypeInstance = new OwnerType()
ownerTypeInstance.id = params.id
// Proceed to the ".save()" step, making sure to pass "insert: true"
...
Piece of cake, huh? Perhaps "Issue #5" is figuring out why you put yourself through all this pain, rather than just writing your CRUD interface by hand with Spring Web MVC (or even vanilla JSP's) in the first place! :)
Support for using SYS_GUID() is dependent upon the Oracle dialect that you are using. Looking at the hibernate source on GitHub it appears that the dialect was only setup to use the Oracle-generated guid in Oracle9Dialect.java and Oracle8iDialect.java. Therefore, it won't work with the 9i or 10g dialects.
You should submit a patch to hibernate which will add the required function(s) to enable the same functionality as the other dialects.

LINQ Query result makes no sense

I am running a simple LINQ query that connects to a view and returns all of the data with the id that I send in.
My simple query is:
var data = db.ViewDataAlls.Where(x => x.guidRequirementId == guidRequirementId);
if I run this query in the database:
select * from viewDataAll where guidrequiremendid = '{Guid Id Sent In Here}'
I get 2 rows back, however the LINQ query is returning 2 rows, but the rows are a duplicate of the first row, not 2 unique rows.
Any ideas?
EDIT: if I run this LINQ Query:
List<string> nums = db.ViewDataAlls
.Where(x => x.guidRequirementId == guidRequirementId)
.Select(x=>x.strNumber).ToList();
I get the individual row numbers, but if I just try to pull the entire row I get a duplicate of the first row multiple times...
I had the same problem. I was ready to conclude that this was a bug in Linq-to-SQL. Direct SQL queries against the view worked, Linqpad queries worked, etc... but for some reason querying against a view sometimes (and not even very often mind you, but when I'd find a particular value that failed, it appeared to always do so) failed. I verified that the query being passed by Linq to the SQL Server was correct (from the SQLServer logs), so it appeared the results were being mangled when they were received by Linq. Querying directly against the view or accessing the contents of the view via a defined association gave the same bad results.
Realizing that the problem lay on the receiving side of the query (after the results were passed back to Linq), I finally tracked it down to the way I had added the view to the dbml. Originally I had dragged the view onto the dbml designer surface, and added an association to the table I wanted to link it to, a basic one-to-many association (using an basic fkid == id relationship). However I couldn't access the view from the table in code. I discovered that I needed to add a primary key to the child (view), so I set the id property as the PK. This seemed to work until I got an unexpected exception when doing a .SingleOrDefault() against the view through the association. Knowing that it should be impossible for my data to have more that one hit for the property I was filtering with, I ran it through the debugger, and sure enough I was getting the right number of results (2 in my case), but the second result was just a copy of the first. The same thing the OP saw.
The solution it turns out is to set all the fields of the view as part of the primary key (in the dbml; I only had 3). Somehow, having the id field as the lone PK was not sufficient for Linq. Once I did this I had no further problems. (It may not be necessary to designate every field as part of the PK, so you may wish to experiment, but just the one id is insufficient apparently).
Note that I did have the view set as "not unique" in the dbml, which one would think would keep this from happening. Apparently not so.
Is ViewDataAlls a view or a table. If it's a view, maybe the sql statement generating that view produces duplicates.
Thanks JHurdlow, you save my day. Looks like LINQ does not use the groupby or order-by in the views. In my case, the SQL Statement in the view was correct and data was presented very well, but for any reason when use LINQ on my MVC3 is different and duplicates rows. In my case I had a view with 5 tables and I had to put all fields as PK on the view at ___DataModel.edmx. Now works fine.
This solution implies that all fields must be not-null, otherwise has to use CASE NULL-THEN END on the View schema.

Autonumbering in new entity

I have an custom entity which needs to have a case number for an XRM Application, can I generate a case number from the Service -> Case.
If this is not possible, how can I do this with a plugin, I've looked at the crmnumbering.codeplex.com but this doesn't support 2011, anybody outthere have a solution or should I rewrite it myself?
thanks
I've ran into this same type of issue (I need a custom # for an entity). Here's how you can do it:
Create an Entity called "Counter"
Add a field called "new_customnumber", make it a string or a number depending on what you want
Create a new record for that entity with whatever you want in the new_customnumber field (let's say "10000")
Create a plugin (EntityNumberGenerator) that goes out and grabs that record (you'll probably want to set the security on this record/entity really tight so no one can mess with the numbers)
On Create of the "custom entity" fire the plugin. Grab the value in new_customnumber save it to the "custom entity" (let's say in a "case" field) increment the new_customnumber and save it to the Counter entity.
Warning, I'm not sure how this is with concurrency. Meaning I'm not sure if 2 custom entities being created at the same time can grab the same number (I haven't ran into an issue yet). I haven't figured out a way to "lock" a field I've retrieved in a plugin (I'm not sure it's possible).
You will be unable to create a custom number for custom entities from the normal area you set a case number.
Look at the CRM2011sdk\sdk\samplecode\cs\plug-ins\accountnumberplugin.cs plugin. It's really similar to what you want.
Ry
I haven't seen one for 2011 yet. Probably easiest to write it yourself.
I've always created a database with a table with a single column which is an IDENTITY column. Write an SP to insert, save the IDENTITY value to a variable, and DELETE the row all within a transaction. Return the variable. Makes for a quick and easy plug-in and this takes care of any concurrency issues.
The performance is fast and the impact to your SQL server is minimal.

Using Linq SubmitChanges without TimeStamp and StoredProcedures the same time

I am using Sql tables without rowversion or timestamp. However, I need to use Linq to update certain values in the table. Since Linq cannot know which values to update, I am using a second DataContext to retrieve the current object from database and use both the database and the actual object as Input for the Attach method like so:
Public Sub SaveCustomer(ByVal cust As Customer)
Using dc As New AppDataContext()
If (cust.Id > 0) Then
Dim tempCust As Customer = Nothing
Using dc2 As New AppDataContext()
tempCust = dc2.Customers.Single(Function(c) c.Id = cust.Id)
End Using
dc.Customers.Attach(cust, tempCust)
Else
dc.Customers.InsertOnSubmit(cust)
End If
dc.SubmitChanges()
End Using
End Sub
While this does work, I have a problem though: I am also using StoredProcedures to update some fields of Customer at certain times. Now imagine the following workflow:
Get customer from database
Set a customer field to a new value
Use a stored procedure to update another customer field
Call SaveCustomer
What happens now, is, that the SaveCustomer method retrieves the current object from the database which does not contain the value set in code, but DOES contain the value set by the stored procedure. When attaching this with the actual object and then submit, it will update the value set in code also in the database and ... tadaaaa... set the other one to NULL, since the actual object does not contain the changed made by the stored procedure.
Was that understandable?
Is there any best practice to solve this problem?
If you make changes behind the back of the ORM, and don't use concurrency checking - then you are going to have problems. You don't show what you did in step "3", but IMO you should update the object model to reflect these changes, perhaps using OUTPUT TSQL paramaters. Or; stick to object-oriented.
Of course, doing anything without concurrency checking is a good way to lose data - so my preferred option is simply "add a rowversion". Otherwise, you could perhaps read the updated object out and merge things... somehow guessing what the right data is...
If you're going to disconnect your object from one context and use another one for the update, you need to either retain the original object, use a row version, or implement some sort of hashing routine in your database and retain the hash as part of your object. Of these, I highly recommend the Rowversion option as well. Using the current value as the original value like you are trying to do is only asking for concurrency problems.

Resources