Question

How can I perform an idempotent insert row using subsonic with a SQL 2008 backend?

e.g.

I have a table "Colors" where name is the primary key.

Color c = new Color;
c.name = "red";
c.Save;

Color c2 = new Color;
c2.name = "red";
c2.Save; // throws duplicate key error;

I know I can just trap the error but I would prefer to do something like REPLACE in MySql

Was it helpful?

Solution

In case you have unique constraints I think that the best option is to handle the validation yourself. Validating if a value will be duplicated on a table is behond the scope of an ORM. ORM is working passing the validation for you to handle when it thows throws the exception and its up to you to behave accordingly.

Lets think a bit about what does it take for you to validate is a value will be a duplicate on the database before the execution of the insert command... 1. You'll have to perform a SELECT for every column that have an unique constraint validating it they already have the value that is about to be inserted. 2. If not, perform the INSERT. 3. If so, throw an Exception?... this is quite what's happening now...

So, let it blow! :) Just be prepared for it to blow (wrap the save within a Try/Catch) and act accordingly.

Cheers! Alex

OTHER TIPS

I didn't reproduce your issue, so I don't have a direct answer for your problem but...

Using strings as PK is not such a good practice, why don't you have it with a INT primary key plus a Description column Varchar? Relations with this table will be way faster as databases index integer much faster than text.

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