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

Laravel migration: unique key is too long, even if specified

Specify a smaller length for your e-mail: $table->string(’email’, 250); Which is the default, actually: $table->string(’email’); And you should be good. For Laravel 5.4 you can find a solution in this Laravel 5.4: Specified key was too long error, Laravel News post: As outlined in the Migrations guide to fix this all you have to do … 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

Unique key with EF code first

Unfortunately you can’t define it as unique key in code first because EF doesn’t support unique keys at all (it is hopefully planned for next major release). What you can do is to create custom database intializer and add unique index manually by calling SQL command: public class MyInitializer : CreateDatabaseIfNotExists<MyContext> { protected override void … Read more