如何使用 subsonic 和 SQL 2008 后端执行幂等插入行?
如何使用 subsonic 和 SQL 2008 后端执行幂等插入行?
例如,
我有一个表“颜色”,其中名称是主键。
Color c = new Color;
c.name = "red";
c.Save;
Color c2 = new Color;
c2.name = "red";
c2.Save; // throws duplicate key error;
我知道我可以捕获错误,但我更喜欢在 MySql 中执行 REPLACE 之类的操作
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您有独特的限制,我认为最好的选择是自己处理验证。
验证某个值是否会在表中重复超出了 ORM 的范围。
ORM 正在努力传递验证,以便您在抛出异常时进行处理,并由您采取相应的行为。
让我们想一下在执行插入命令之前需要做什么来验证一个值是否会在数据库上重复......
1. 您必须对具有唯一约束的每一列执行 SELECT,以验证它们已经具有要插入的值。
2. 如果没有,则执行 INSERT。
3. 如果是这样,抛出一个异常?...这就是现在正在发生的事情...
所以,让它爆炸吧! :)
只要做好准备,让它爆炸(将保存包含在 Try/Catch 中)并采取相应的行动。
干杯!
亚历克斯
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
我没有重现您的问题,所以我没有直接回答您的问题,但是...
使用字符串作为 PK 并不是一个好的做法,为什么不使用 INT 主键加上说明列 Varchar?与此表的关系将更快,因为数据库索引整数比文本快得多。
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.