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 回答