开发者

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

开发者 https://www.devze.com 2022-12-27 04:17 出处:网络
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 re

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, strin开发者_如何学Cg 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;
        }
    }
}


In EF 4, you can do:

var location = context.Locations.Where(l => l.RegionId == regionId)
                                .DefaultIfEmpty(new Location 
                                                    { 
                                                        RegionId = regionId, 
                                                        Name     = name
                                                    }).First();
someOtherObject.Location = location;
context.SaveChanges();

...which works in either case.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号