Linq to SQL - Possible to generate Unique Key constraint on DB via entity attribute
In Linq to Sql, Is there any way to define attributes on an entity that indicate that it should be unique (a开发者_如何学运维nd 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; }
}
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.
精彩评论