问题
In an Oracle database, that has an ID column defined as a number:
...and a corresponding sequence for the table...:
How do I make sure the ID column gets the next value in the sequence?
using (var db = new MyOracleDb()){
var user= new User(){ first_name = 'Abe', last_name = 'Lincoln'};
//Do something here with the sequence and set the ID?
db.User.Add(user);
db.SaveChanges();
}
I am using the latest Oracle.ManagedDataAccess and Oracle.ManagedDataAccess.EntityFramework + EF6x.
回答1:
This is not an EF issue, as there is no auto increment in oracle. You will have to either get the sequence value manually, or create a trigger to set it for you.
Update
In order to get the sequence value you have two options - either create a stored procedure, that returns the value - or create a .Net function ( doesn't really have to be in a function, it's just simpler) that calls raw SQL like this:
Database.SqlQuery<int>("SELECT SEQ_SOMESEQ.NEXTVAL FROM dual");
I personally had many issues with oracle functions and EF, so I would go with the raw sql.
回答2:
Just FYI, With Entity Framework I had issues with unique constraints. For future readers if you're still having unique constraint issues. Please make sure you change the property "StoreGeneratedPattern" to your requirement.
For me I was adding MAX(ID) + 1 and had StoreGeneratedPattern set as Identity which started to work fine but after sometime break the whole program by throwing the same unique constraint issue, which when I checked database was definitely not the case. It was something that most developers didn't pay attention to.
I've changed it to "None" So I have control over it to what to add rather than entity framework breaking it after every few days. Entity Framework Property Picture
回答3:
If you create the trigger on Oracle's side you don't have to worry about it on your code. It works as if it did have an Identity.
来源:https://stackoverflow.com/questions/40382947/how-to-insert-identity-value-in-oracle-using-entity-framework-using-a-sequence