How do I achieve a 'select or insert' task using LINQ to EF?

Posted by ProfK on Stack Overflow See other posts from Stack Overflow or by ProfK
Published on 2010-04-13T00:02:55Z Indexed on 2010/04/13 13:43 UTC
Read the original article Hit count: 622

Filed under:
|

I have an import process with regions, locations, and shifts, where a Shift object has a Location property, and a Location object has a Region property. If a region name does not exist, I create the region, and like wise a location. I thought I could neatly encapsulate the 'Select if exists, or create' logic into helper classes for Region and Location, but if I use local data contexts in these classes I run into attach and detach overheads that become unpleasent. If I include a data context dependency in these classes, my encapsulation feels broken.

What is the ideal method for achieving this, or where is the ideal place to place this functionality? In my example I have leaned heavily on the foreign key crutch provided with .NET 4.0, and simply avoided using entities in favour of direct foreign key values, but this is starting to smell.

Example:

public partial class ActivationLocation
{
    public static int GetOrCreate(int regionId, string name)
    {
        using (var ents = new PvmmsEntities())
        {
            var loc = ents.ActivationLocations.FirstOrDefault(x => x.RegionId == regionId && x.Name == name);
            if (loc == null)
            {
                loc = new ActivationLocation {RegionId = regionId, Name = name};
                ents.AddToActivationLocations(loc);
                ents.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
            }
            return loc.LocationId;
        }
    }
}

© Stack Overflow or respective owner

Related posts about entity-framework

Related posts about .NET