0

既存の値を明示的にチェックすることなく、一意の値を挿入する方法を知っている人はいますか?

私はこれを機能させることができますが、私が書かなければならなかったコードにはあまり感銘を受けません. 基本的に、コンテナの一意の値をチェックするヘルパー関数を作成しました。

構造はかなり基本的です。

[エントリ] *<----->* [ユニーク値]

メインコード

public static void ImportStuff ()
{
    //Generate a list of importable items
    List<DtoItems> items = DtoItemGetter.GetItems();
    using( var container = new MyEntities() )
    {
        foreach( var item in items )
        {
            Entry newEntry = CreateNewEntry( item );

            //******** 
            // Here's the call to my helper method to check 
            // for the uniqueness of the values on the item I am importing
            //******** 
            item.UniqueValuesList.ForEach( 
                uv => HelperMethod( container, newEntry, uv ) );

            containter.AddToEntries( newEntry );

            //Less important... but it would be nice if I didn't 
            // have to save everytime I add an new entry... but 
            // this necessary for the Helper check.
            container.SaveChanges();
        }
    }
}

ヘルパー メソッド

public static void HelperMethod( 
    MyEntities container, Entry newEntry, string checkValue )
{
    UniqueItem unique = null;

    //Have to check to see if it already exists in the DB
    container.uniqueItems.ForEach( uv => { 
        if( uv.Name == checkValue )
        {
            unique = uv;
        } } );

    //Here's the money, either add the one I found, or 
    //create a new one... meh
    newEntry.UniqueItems.Add( 
        unique ?? new UniqueItem { Name = checkValue } );
}

うまくいけば、これは十分に理にかなっています。

4

1 に答える 1

1

エンティティ フレームワークは一意の制約をまだサポートしていません - http://blogs.msdn.com/b/efdesign/archive/2011/03/09/unique-constraints-in-the-entity-framework.aspx

したがって、一意の制約を使用する場合は、データベースに手動で制約を設定し、手動で確認する必要があります。

EF Codefirstは一意のプロパティを検証しますか?

于 2012-08-12T07:43:49.463 に答える