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; }
}
2
  • stackoverflow.com/questions/4014482/… : in short, enforce at the database, catch any errors in the middle tier. Commented Apr 25, 2011 at 0: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. Commented Apr 25, 2011 at 15:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It's being answered around 10 years back, now EF has, check this: stackoverflow.com/a/72208419/4393351

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.