开发者

Best way to handle unique constraints when using Entity Framework

开发者 https://www.devze.com 2023-01-23 00:20 出处:网络
I\'m using Entity Framework 4.0 to access data in a table with a unique column constraint.If the constraint is violated, an exception occurs when I call SaveChanges(), as expected.My que开发者_如何学运

I'm using Entity Framework 4.0 to access data in a table with a unique column constraint. If the constraint is violated, an exception occurs when I call SaveChanges(), as expected. My que开发者_如何学运维stion is whether I should allow the exception to be thrown in the first place. I could alternatively do a select to avoid inserting the duplicate data (I assume a transaction would be necessary).

What's the generally accepted best practice in this scenario?


Avoiding an exception is usually a good idea - throwing an exception is a rather elaborate and time and resource intensive operation. So if you can easily check whether a unique key value already exists, then I would probably do that. Assuming you have a unique index or unique constraint on that column at the database level, then (at least for SQL Server) already have an index on that column, so checking for a specific value would be fairly simple and would not have a huge performance impact.

The other question is: how often do you think this would happen? Once a day? Once every couple of weeks? Several times a minute? If it happens only fairly infrequently - once in a blue moon - I wouldn't bother trying to check first - in that case, just let the exception happen and handle it.

So I guess it's really a matter of how expensive is it to check first, and how often does it happen? If you can check it very easily --> do so, by all means! But if it's a rather elaborate operation to check, and it happens only very rarely, then just handle the exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消