如何使用LINQ to SQL实施唯一约束 [英] How to enforce unique constraint with LINQ to SQL
问题描述
我想使用LINQ to SQL对两列实施唯一约束.我在SQL表上配置了约束,但是有没有办法将它与LINQ to SQL一起使用?
I'd like to enforce a unique constraint on two columns with LINQ to SQL. I have got a constraint configured on a SQL table, but is there a way to use it with LINQ to SQL?
唯一约束应用于两列,这两列都是外键.
Unique constraint is applied to two columns, both of which are foreign keys.
谢谢
我可以捕获异常,那就是抛出非常特定的异常.另一种方法是在运行任何更新/插入之前检查表的状态.对于一个非常简单的任务,所有工作似乎都太多了.
I could catch exception, that's if a very specific exception gets thrown. Alternative is to check state of the table before running any updates/inserts. All seems to be like too much work for a very simple task.
推荐答案
在我看来,L2S不应对此进行实际实施.您的数据库应该通过唯一约束来执行此操作.然后,当您尝试通过L2S进行插入或更新时,可以简单地捕获在调用SubmitChanges()时返回的异常(如果有).
In my opinion, L2S should not be doing the actual enforcement of this. Your database should be doing it via a unique constraint. Then, when you attempt to do an insert or update via L2S, simple catch the exception (if any) being returned when you call SubmitChanges().
这篇关于如何使用LINQ to SQL实施唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!