简体   繁体   中英

Entity Framework how do I INSERT unique value on many to many relationship without having to do manual check

Does anyone know how to insert unique values without explicitly having to check for an existing value?

I am able to make this work, but I am less than impressed with the code I had to write. Basically I created a helper function to check a unique value on my container.

The structure is pretty basic.

[ Entry ] *<----->* [ UniqueValue ]

Main code

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();
        }
    }
}

Helper Method

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 } );
}

Hopefully this makes enough sense.

Entity framework doesn't support unique constraints yet - http://blogs.msdn.com/b/efdesign/archive/2011/03/09/unique-constraints-in-the-entity-framework.aspx

So if you want to use unique constraints you should set the constraint on the database manually and check by hand.

EF Codefirst validate unique property?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM