Question

I have a very simple asp.net mvc web app which uses castle active record, on top of MySql.

The users of the app want to now define the primary key for one of the entities manually (it was the default of autonumber). No problem I thought, I will simple change the primary key attribute from [PrimaryKey] to [PrimaryKey (PrimaryKeyType.Assigned)] and modify the database schema (okay I know this could be considered a flawed approach but that is not the point of this question)

After trying this, new entities would never get persisted to the database when calling their .Create() method, even though I create a sessionscope per request in OnBeginRequest and OnEndRequest using code identical to here. The same code worked fine before I altered the [Primary Key] attribute.

If I call .CreateAndFlush() instead of Create(), the entities are persisted to the db. I thought the changes in Create() would be persisted when the sessionscope ends. Why aren't they... am I misunderstanding how this should work?

Was it helpful?

Solution 2

Turned out to be pebcak. I had forgotten that I'd written some code which checks that the new primary key does not exist. That code of course needed its own sessionscope. As soon as I did that everything worked, i.e. calling .create would persist the object to the DB.

Two lessons learned from this:

  1. Next time post my code on SO.
  2. Don't make late night code changes that I may otherwise forget about...

OTHER TIPS

For a generated Key ActiveRecord knows that 0/NULL/{0000-0000-0000-0000}/etc. are the empyt values and that the object is transient and needs to be created. It does not know it the PrimaryKey is Assigened. But you can tell ActiveRecord what the empty value is, just use the following named parameter for your PrimaryKeyAttribute.

[PrimaryKey(PrimaryKeyType.Assigned, UnsavedValue="")]

Greeetings Juy Juka

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top