How can I catch UniqueKey Violation exceptions with EF6 and SQL Server?

With EF6 and the DbContext API (for SQL Server), I’m currently using this piece of code: try { // Some DB access } catch (Exception ex) { HandleException(ex); } public virtual void HandleException(Exception exception) { if (exception is DbUpdateConcurrencyException concurrencyEx) { // A custom exception of yours for concurrency issues throw new ConcurrencyException(); } else … Read more

Unique keys in Entity Framework 4

The Entity Framework 6.1 now supports uniques with both Data Annotations and Fluent API. Data Annotations (Reference) public class MyEntityClass { [Index(IsUnique = true)] [MaxLength(255)] // for code-first implementations public string MyUniqueProperty{ get; set; } } Fluent API (Reference) public class MyContext : DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder .Entity<MyEntityClass>() .Property(t => … Read more

INSERT … ON DUPLICATE KEY (do nothing)

Yes, use INSERT … ON DUPLICATE KEY UPDATE id=id (it won’t trigger row update even though id is assigned to itself). If you don’t care about errors (conversion errors, foreign key errors) and autoincrement field exhaustion (it’s incremented even if the row is not inserted due to duplicate key), then use INSERT IGNORE like this: … Read more

Unique Key constraints for multiple columns in Entity Framework

With Entity Framework 6.1, you can now do this: [Index(“IX_FirstAndSecond”, 1, IsUnique = true)] public int FirstColumn { get; set; } [Index(“IX_FirstAndSecond”, 2, IsUnique = true)] public int SecondColumn { get; set; } The second parameter in the attribute is where you can specify the order of the columns in the index. More information: MSDN