我首先尝试使用fluent配置强制执行列的唯一约束。有没有比在业务逻辑中实现它或使用下面的东西更好的方法
context.ObjectContext.ExecuteStoreCommand("CREATE UNIQUE CONSTRAINT...");
或者我想知道是否不可能使用流畅的配置实现独特的约束?
编辑:
通过流畅的配置确认无法做到这一点。但是我又想知道最好的方法是什么?并且想知道EF不支持这一点的原因。
答案 0 :(得分:2)
在此示例中,您可以了解如何定义唯一键属性并在任何实体中使用它。
http://code.msdn.microsoft.com/windowsdesktop/CSASPNETUniqueConstraintInE-d357224a
答案 1 :(得分:1)
我之前发生过这个问题
它无法使用流畅的API实现唯一约束。所以,你使用的方式是正确的!
答案 2 :(得分:1)
这可以使用DbMigrations ...
public override void Up()
{
CreateIndex("dbo.MyTableName", "MyColumnName", unique: true);
}
答案 3 :(得分:1)
可以使用自定义扩展方法完成:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration.Configuration;
internal static class TypeConfigurationExtensions
{
public static PrimitivePropertyConfiguration HasUniqueIndexAnnotation(
this PrimitivePropertyConfiguration property,
string indexName,
int columnOrder = 0)
{
var indexAttribute = new IndexAttribute(indexName, columnOrder) { IsUnique = true };
var indexAnnotation = new IndexAnnotation(indexAttribute);
return property.HasColumnAnnotation("Index", indexAnnotation);
}
}