问题
I'm using ActiveRecord by CastleProject with MySQL in my solution. I wanted to retrieve the last insert ID, so I did something like this:
[ActiveRecord]
public class UserDb : ActiveRecordBase<UserDb>
{
[PrimaryKey]
public uint Id { get; set; }
[Property]
public int OtherStuff { get; set; }
}
public void Blablabla()
{
UserDb user = new UserDb();
user.OtherStuff = 123;
user.CreateAndFlush();
Console.WriteLine( user.Id );
}
Sometimes, it outputs the correct ID, but sometimes, it just outputs 0. Did I miss anything?
Note: The reason I did this is because we had several server connected to the same database at the same time, and I wanted a unique id generator. For unique, I mean unique among those servers. If there're other solutions to maintain a unique id generator among several servers, I will be very appreciated.
Thanks guys!
回答1:
If you want to have a unique ID among several servers, you might consider using a GUID instead of an int. If, however, you're just trying to get the ID of the item you just inserted, you could just refresh it with user.Refresh()
回答2:
Castel.ActiveRecord (or better NHibernate) gives you multiple options to generate primary keys, you should have a look at the PrimaryKeyType-Enum.
GUID is the easiest one, needing nothing more then to make the primary-key-Property of the type System.Guid and adjust the column in the database. (I am not sure wich type you need in the database, I allways use VARCHAR/CHAR/etc.)
If you want to keep the uint you are using at the moment, then I would suggest to use HiLo.
[PrimaryKey(Generator=PrimaryKeyType.HiLo)]
public virtual uint Id{get;set;}
In the database:
CREATE TABLE hibernate_unique_key( next_hi NUMERIC(18, 0) );
INSERT INTO hibernate_unique_key VALUES(1);
-- script from ms-sql-express, I am not sure if there is a difference for mysql
Greetings Juy Juka
回答3:
I've been bitten by the same issue. However, my issue grew and I found what seems to be the real issue; nHibernate is not thread-aware. I'm assuming your code is multi-threaded, if so you need to make use of 'using(new SessionScope())' blocks for database access in other threads.
In my case Castle would return IDs from other tables after saving, that really drove me crazy.
来源:https://stackoverflow.com/questions/8950883/how-to-retrieve-the-last-insert-id-in-castle-activerecord