How can I perform an idempotent insert row using subsonic with a SQL 2008 backend?
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 开发者_StackOverflow中文版= "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
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
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.
精彩评论