5

最初にコードの流暢な構成を使用して、列の一意の制約を適用しようとしています。ビジネスロジックで実装するか、以下のようなものを使用するよりも良い方法はありますか

context.ObjectContext.ExecuteStoreCommand("CREATE UNIQUE CONSTRAINT...");

または、流暢な構成を使用して一意の制約を実装できないかどうか疑問に思っていましたか?

編集 :

これは流暢な構成では不可能であることが確認されています。しかし、もう一度、これを行うための最良の方法は何だろうと思っています。EFがこれをサポートしていない理由を知りたいです。

4

4 に答える 4

1

これはDbMigrationsで可能です...

public override void Up()
{
    CreateIndex("dbo.MyTableName", "MyColumnName", unique: true); 
}
于 2014-02-13T19:16:51.083 に答える
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);
    }
}

ここで完全な回答を確認してください: https://stackoverflow.com/a/25779348/111438

于 2014-09-11T04:59:50.867 に答える
1

以前にこの問題が発生しました

流暢な API を使用して一意の制約を実装することはできません。</p>

だから、あなたが使った方法は正しいです!

于 2013-03-18T13:12:33.497 に答える