既存の値を明示的にチェックすることなく、一意の値を挿入する方法を知っている人はいますか?
私はこれを機能させることができますが、私が書かなければならなかったコードにはあまり感銘を受けません. 基本的に、コンテナの一意の値をチェックするヘルパー関数を作成しました。
構造はかなり基本的です。
[エントリ] *<----->* [ユニーク値]
メインコード
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 } );
}
うまくいけば、これは十分に理にかなっています。