Why do I get concurrent exception in Entity Framework when I'm the only user?

0

I just graduated and I'm working on my first project.

I searched a lot and tried many solutions but none of them seemed to solve the issue. I'm new to .NET and Entity Framework and I'm trying to insert a new row into an existing table via POST call with EF, but I keep getting the following exception even though I'm the only user currently using this database (inserting a row directly to DB is successful)

This is the exception I get:

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException
HResult=0x80131501
Message=Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.
Source=EntityFramework

StackTrace:

at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at Em_Habanim_Api.Controllers.TherapyController.PostTherapyMeetingSet(TherapyMeetingSet t) in Q:\a_Tech_App_2018\user\Aim Habanim Server\Em_Habanim_Api\Controllers\TherapyController.cs:line 127
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClassc.b__6(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)

Inner Exception 1:

OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.

I have tried posting in the two following ways:

[Route("api/therapySets/{id}/func1")]
public void PostTherapyMeetingSet(TherapyViewModel t)
{
    using (Em_Habanim_Entities db = new Em_Habanim_Entities())
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        TherapyMeetingSet therapySet = new TherapyMeetingSet();
        therapySet.Id = t.Id;
        therapySet.TherapistId = t.TherapistID;
        therapySet.ClientId = t.ClientID;
        therapySet.Date = t.Date;
        therapySet.Comments = t.Comments;

        db.TherapyMeetingSets.Add(therapySet);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = therapySet.Id }, therapySet);
    }
}

Here is the TherapyViewModel class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BL.model;

namespace Em_Habanim_Api.Models
{
    public class TherapyViewModel
    {
        public TherapyViewModel(TherapyMeetingSet t)
        {
            this.Id = t.Id;
            this.TherapistID = t.TherapistId;
            this.ClientID = t.ClientId;
            this.Date = t.Date;
            this.Comments = t.Comments;
        }

        public TherapyViewModel()
        {
        }

        public int Id { get; set; }
        public int TherapistID { get; set; }
        public int ClientID { get; set; }
        public DateTime Date { get; set; } 
        public string Comments { get; set; }
    }
}

I have also tried without using the TherapyViewModel class but I got the same exception:

[Route("api/therapySets/{id}/func1")]
public void PostTherapyMeetingSet(TherapyMeetingSet t)
{
    using (Em_Habanim_Entities db = new Em_Habanim_Entities())
    {
        db.TherapyMeetingSets.Add(t);
        db.SaveChanges();
    }
}

Here is the table definition:

CREATE TABLE [dbo].[TherapyMeetingSet] 
(
    [Id]          INT IDENTITY(1,1) NOT NULL,
    [TherapistId] INT           NOT NULL,
    [ClientId]    INT           NOT NULL,
    [Date]        DATETIME      NOT NULL,
    [Comments]    NVARCHAR(100) NULL,

    CONSTRAINT [PK_MeetingSet] 
        PRIMARY KEY CLUSTERED ([Id] ASC),

    CONSTRAINT [FK_TherapistMeeting] 
        FOREIGN KEY ([TherapistId]) REFERENCES [dbo].[TherapistSet] ([Id]),
    CONSTRAINT [FK_PersonTherapyRequest] 
        FOREIGN KEY ([ClientId]) REFERENCES [dbo].[PersonSet] ([Id])
);
GO

CREATE TRIGGER ClientChildOrMotherTrigger 
ON therapyMeetingSet
INSTEAD OF INSERT
AS
    DECLARE @ClientId INT;
    DECLARE @therapistId INT;
    DECLARE @Date DATE;
    DECLARE @Comments NVARCHAR(100);

    SELECT @ClientId = i.ClientId 
    FROM inserted i;

    SELECT @therapistId = i.TherapistId 
    FROM inserted i;

    SELECT @Date = i.Date 
    FROM inserted i;

    SELECT @Comments = i.Comments 
    FROM inserted i;

    IF EXISTS (SELECT id FROM ChildSet WHERE id = @ClientId) OR
       EXISTS (SELECT id FROM MotherSet WHERE id = @ClientId)
       INSERT INTO TherapyMeetingSet 
       VALUES (@therapistId, @ClientId, @Date, @Comments)
    ELSE
       PRINT 'Client ID is invalid'

Any idea what is causing this error?

.net
sql-server
entity-framework
asked on Stack Overflow Jun 3, 2018 by C R • edited Jun 4, 2018 by C R

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0