I have an import process with regions, locations, and shifts, where the Shift object has a Location property and the Location object has a Region property. If the name of the region does not exist, I create a region and, as wise, a place. I thought I could carefully encapsulate the "Select, if exists, or create" logic in the helper classes for the region and location, but if I use local data contexts in these classes, I encounter an application and disabling overhead that becomes inconvenient. If I include a data context dependency in these classes, my encapsulation will be broken.
What is the ideal method to achieve this, or where is the ideal place to place this function? In my example, I relied heavily on the foreign key crutch that came with .NET 4.0 and simply avoided using entities in favor of the direct foreign key values, but it starts 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;
}
}
}
source
share