Linq to SQL - 可以通过实体属性在数据库上生成唯一键约束
在 Linq to Sql 中,有没有办法在实体上定义属性,表明它应该是唯一的(并且在生成数据库时也会在数据库中生成唯一约束)
注意:我希望生成唯一键约束,而不是我的实体上的另一个主键)
即,我希望在“描述”属性上有一个属性,以指示根据我们的业务规则它应该是唯一的。
[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; }
}
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; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Linq-To-SQL(以及实体框架)不支持唯一键,因此没有注释可以确保在数据库中为您生成唯一约束。您必须始终使用某些部署后脚本添加唯一约束/索引。
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.