2

In Linq to Sql, Is there any way to define attributes on an entity that indicate that it should be unique (and will also generate a unique constraint in the database when generating the database)

Note: I'm looking to generate a unique key constraint, not another primary key on my entity)

I.e. I would like to have an attribute on the Description property to indicate that it should be unique, according to our business rules.

[Table(Name = "ProductCategory")]
public class ProductCategory
{
    // Generate a primary key
    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert, Name="ProductCategoryId")]
    public int ProductCategoryId { get; set; }

    [Column(CanBeNull = false, ATTRIBUTE TO GENERATE UNIQUE CONSTRAINT FOR THIS PROPERTY/COLUMN]
    public string Description { get; set; }

    [Column(CanBeNull = false)]
    public DateTime CreatedDate { get; set; }

    [Column(CanBeNull = true)]
    public DateTime? ModifiedDate { get; set; }
}
Danny Varod
  • 17,324
  • 5
  • 69
  • 111
contactmatt
  • 18,116
  • 40
  • 128
  • 186
  • http://stackoverflow.com/questions/4014482/how-to-enforce-unique-constraint-with-linq-to-sql : in short, enforce at the database, catch any errors in the middle tier. – Mitch Wheat Apr 25 '11 at 00:55
  • See, I like having my constraints defined in my entities because I can generate the database and be done, rather than generating the database and then worrying about crearting/scripting unique constraints. Same thing with the PK that I have in the entity above, it could be argued that this should be scripted out/added after, but its just so more nice and convenient being able to attach it to my entity. – contactmatt Apr 25 '11 at 15:50

1 Answers1

2

Linq-To-SQL (as well as Entity Framework) has no support for unique keys and because of that there is no annotation which will ensure that unique constraint will be generated in the database for you. You must always add unique constraints / indexes with some post deployment script.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • It's being answered around 10 years back, now EF has, check this: https://stackoverflow.com/a/72208419/4393351 – KushalSeth May 11 '22 at 23:08