g_b
g_b

Reputation: 12438

Checking if added items exists prior to calling SaveChanges

I have this code that inserts a room if the room name does not yet exist:

private bool TryGetRoom(Room room, out int? roomId)
{
    bool success = false;
    roomId = null;
    if (room != null)
    {
        // Check if room already exists
        var foundRoom = _context.Rooms.Where(rm => String.Equals(rm.Name, room.Name, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
        if (foundRoom == null)
        {
            // Create room
            var roomToAdd = _mapper.Map<dataModels.Room>(room);
            roomToAdd.CompanyId = _context.TenantId;
            _context.Add(roomToAdd);

            roomId = roomToAdd.Id;
            success = true;
        }
        else
        {
            roomId = foundRoom.Id;
            success = true;
        }
    }
    return success;
}

My problem is this function is called inside a loop inserting rooms. Sometime, the items in the loop has same room name, I thought even though I haven't called SaveChanges yet, this line:

var foundRoom = _context.Rooms.Where(rm => String.Equals(rm.Name, room.Name, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();

will see the rooms i've added earlier even though SaveChanges will be called once the loop is done.

Is this not correct? I can ofcourse create a variable to track the inserted items but I thought it would be tracked by the context and it would see I've inserted a room with a name earlier?

Upvotes: 0

Views: 20

Answers (1)

Embri
Embri

Reputation: 622

Inside _context.Rooms.Local you can find entities that are added/modified, i think it could be what you need.

More about local data: http://www.entityframeworktutorial.net/EntityFramework4.3/local-data.aspx

Upvotes: 1

Related Questions