开发者

Entity Framework - Making a column auto-incremement

开发者 https://www.devze.com 2023-04-11 13:27 出处:网络
So I\'m using the Entity Framework and we have a modal for a table called TPM_PROJECTVERSIONNOTES.This table has a column called NOTEID which is a number.Right now, when we create a new row, we get th

So I'm using the Entity Framework and we have a modal for a table called TPM_PROJECTVERSIONNOTES. This table has a column called NOTEID which is a number. Right now, when we create a new row, we get the next available number with this code:

note.NOTEID = (from n in context.TPM_PROJECTVERSIONNOTES
               orderby n.NOTEID descending
               select n.NOTEID).Max() + 1;

To me, this seems incredibly hacky (I mean you have to do an entire SQL query just to get the next value). Plus, it's incredibly dangerous; it's not thread safe or transaction safe. I've already found 9 instances in the DB that have the same NOTEID! Good thing no one even thought to put a UNIQUE constraint on that column... sigh.

So anyway, I've added a new sequence to the database:

CREATE SEQUENCE TPM_PROJECTVERSIONNOTES_SEQ START WITH 732 INCREMENT BY 1;

Now my question:

How do I instruct the Entity framework to use TPM_PROJECTVERSIONNOTES_SEQ.nextval when inserting a row into this table? Basically, I just don't want to specify a NOTEID at all and开发者_JAVA技巧 I want the framework to take care of it for me. It's been suggested I use a trigger, but I think this is a bit hacky and would rather have to Entity framework just create the correct SQL in the first place. I'm using Oracle 11g for this.


While this may still fall into what you call the 'hacky' category, you can avoid using triggers to call the nextval, but you must utilize a stored procedure to handle the insert (whereas it will call the nextval in lieu of using a TRIGGER). (I guess this could fall more into a TAPI/XAPI category)

Check out the recent article TECHNOLOGY: Oracle Data Provider for .NET

it explains (and contains samples) to using a stored procedure to handle the insert, calling the sequence, and mapping it back to the ODP EF BETA.

This obviously does not have the ODP EF Beta do the SQL for nextval, but it is an alternative. (look at this forum, it does appear that most of the EF Oracle frameworks fall victim to this-- devart etc {https://forums.oracle.com/forums/thread.jspa?threadID=2184372} )

0

精彩评论

暂无评论...
验证码 换一张
取 消