Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6016087
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T02:55:57+00:00 2026-05-23T02:55:57+00:00

I have a data-structure such that: SecurityPolicy 1<—* SecurityPolicyRule Therefore, a SecurityPolicy can have

  • 0

I have a data-structure such that:

SecurityPolicy 1<—* SecurityPolicyRule

Therefore, a SecurityPolicy can have 0, one or many SecurityPolicyRules.

I am using Julie Lerman’s Entity Framework book to implement some degree of concurrency checking, TDD and POCO support.

I understand that each table should have a rowversion/timestamp field, which is marked as ConcurrencyMode==Fixed.

I have decided to implement the CUD in Stored Procedures. My UPDATE Sproc is as follows:

create PROCEDURE dbo.sp_M2_Core_UpdateSecurityPolicy
    @ID int,
    @Name nvarchar(256),
    @Comment nvarchar(max)=null,
    @timestamp timestamp
AS

declare @nameExists nvarchar(256)

    select @nameExists= [Name] from M2_Core_SecurityPolicy where [Name]=@Name and [ID]<>@id
    if (not @nameExists is null)
    begin
        raiserror (N'Name is already in use: %s',
        11,
        1,
        @Name)
    end
    else
    begin
        update M2_Core_SecurityPolicy
            set [Name]=@Name,
                [Comment]=@Comment
                where id=@id and [timestamp]=@timestamp
        IF @@ROWCOUNT>0
            SELECT [Timestamp] AS newTimeStamp FROM M2_Core_SecurityPolicy WHERE id=@id
    end

go

create PROCEDURE dbo.sp_M2_Core_UpdateSecurityPolicyRule    
    (
    @id int,
    @RoleName nvarchar(256),
    @Rank int,
    @CanReadExecute bit=null,
    @CanWrite bit=null,
    @CanDelete bit=null,
    @CanExport bit=null,
    @Timestamp timestamp
    )

AS

    declare @roleExists nvarchar(256)
    declare @securityPolicyID int

    select @roleExists= [RoleName] from vw_aspnet_Roles where [RoleName]=@RoleName
    if (@roleExists is null)
    begin
        raiserror (N'Role is not defined: %s',
        11,
        1,
        @roleName)
    end
    else
    begin
        select @securityPolicyID=[SecurityPolicyID] from M2_Core_SecurityPolicyRule where [id]=@id

        -- move all other rules up in priority
        IF (SELECT COUNT(*) FROM M2_Core_SecurityPolicyRule WHERE [ID]<>@ID AND [SecurityPolicyID]=@SecurityPolicyID AND [Rank]=@Rank) > 0 
        BEGIN
            UPDATE M2_Core_SecurityPolicyRule
                SET [Rank]=[Rank]+1
                WHERE [Rank] >= @rank
                    AND [SecurityPolicyID]=@SecurityPolicyID
                    AND [ID]<>@ID
        END

        update M2_Core_SecurityPolicyRule
            set [RoleName]=@RoleName,
                [Rank]=@Rank,
                [CanReadExecute]=@CanReadExecute,
                [CanWrite]=@CanWrite,
                [CanDelete]=@CanDelete,
                [CanExport]=@CanExport              
                where id=@id and [timestamp]=@timestamp
        IF @@ROWCOUNT>0
            SELECT [Timestamp] AS newTimeStamp FROM M2_Core_SecurityPolicyRule WHERE id=@id

    end

    RETURN

go

I am testing this using some code that:

  1. Creates a Security Policy
  2. Adds a created Security Policy Rule to the Security Policy
  3. Adds the Security Policy
  4. Saves the updates
  5. Adds 1 to the Rank of the Security Policy Rule
  6. Saves the updates

The test is below:

[TestMethod()]
        public void AddWithSecurityPolicyRuleChangeRankTest()
        {
            ICoreContext coreContext = new CoreEntities(_coreDbConnectionString);
            CoreUnitOfWork coreUnitOfWork = new CoreUnitOfWork(coreContext);
            SecurityPolicyRepository target = new SecurityPolicyRepository(coreUnitOfWork);
            int originalCount = coreContext.SecurityPolicies.Count();
            string securityPolicyName = "addwithsecuritypolicyrulechangeruletest";
            int originalRank = 1;
            SecurityPolicy entity = new SecurityPolicy()
            {
                Comment = null,
                Name = securityPolicyName,
                SecurityPolicyRules = new FixUpCollection<SecurityPolicyRule>()
            };
            entity.SecurityPolicyRules.Add(
                new SecurityPolicyRule()
                {
                    CanDelete = null,
                    CanExport = null,
                    CanReadExecute = null,
                    CanWrite = null,
                    Rank = originalRank,
                    RoleName = "User"
                });
            target.Add(entity);
            coreUnitOfWork.Save();

            entity.SecurityPolicyRules[0].Rank=originalRank+1;
            coreUnitOfWork.Save(); // <-- exception thrown here
            SecurityPolicy savedSecurityPolicy = target.GetAll().Single(q => q.Name.Equals(securityPolicyName, StringComparison.CurrentCultureIgnoreCase));
            Assert.AreEqual(originalRank+1,savedSecurityPolicy.SecurityPolicyRules[0].Rank);
        }

However, when I run this, it throws an exception at the highlighted line. The exception is:

System.Data.OptimisticConcurrencyException
was unhandled by user code
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.
Refresh ObjectStateManager entries.
Source=System.Data.Entity
StackTrace:
at System.Data.Mapping.Update.Internal.UpdateTranslator.ValidateRowsAffected(Int64
rowsAffected, UpdateCommand source)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager
stateManager, IEntityAdapter adapter)
at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager
entityCache)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions
options)
at System.Data.Objects.ObjectContext.SaveChanges()
at MIGTurbo2.Core.Data.CoreEntities.Save()
in
D:\dev\migturbo2.0\MIGTurbo2.Core\Data\Core.Context.cs:line
92
at MIGTurbo2.Repositories.CoreUnitOfWork.Save()
in
D:\dev\migturbo2.0\MIGTurbo2.Repositories\CoreUnitOfWork.cs:line
26
at MIGTurbo2.Core.Tests.IntegrationTests.SecurityPolicyRepositoryTest.AddWithSecurityPolicyRuleChangeRankTest()
in
D:\dev\migturbo2.0\MIGTurbo2.Core.Tests\IntegrationTests\SecurityPolicyRepositoryTest.cs:line
524 InnerException:

And sure enough, no data has changed. ie. The [Rank] is still 1 from the first update (therefore, the INSERT). However, running it through SQL Profiler and Ayende’s EF Profiler, no calls to the database are even made to make the UPDATE. So the relevance of the timestamp/rowversion is surely … irrelevant?

What could be causing this? I don’t want to have to Refresh the DB on every Save!

Update 1

Having run the SQL that should execute:

declare @t timestamp
select @t=[timestamp] from M2_Core_SecurityPolicyRule where ID=1
exec [sp_M2_Core_UpdateSecurityPolicyRule] @id=1, @roleName='User',@Rank=2,@Timestamp=@t

It works fine. There is something inside EF occurring that is blocking the call

Update 2

By breaking through the code, I find that the following occurs:

  1. The item is created (obviously, Timestamp is null)
  2. The item is added (Timestamp still null)
  3. The changes are saved (this issues the INSERT)
  4. The [Timestamp] field is then NOT UPDATED from the DB
  5. Therefore, the subsequent UPDATE fails, as [Timestamp] IS NULL

So why would the [Timestamp] field not be updated?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T02:55:58+00:00Added an answer on May 23, 2026 at 2:55 am

    It seems that there I might have misunderstood Julie Lerman’s book or there is a slight change required to how she implements her Stored Procedures.

    I have changed the Model and Stored Procedures such that the SProcs return the Timestamp and the Model picks it up. This therefore means that the [Timestamp] field will not be null.

    So the INSERT SProc now looks like:

    create PROCEDURE dbo.sp_M2_Core_InsertSecurityPolicy
        @Name nvarchar(256),
        @Comment nvarchar(max)=null
    AS
    
        declare @nameExists nvarchar(256)
        declare @id int 
    
        select @nameExists= [Name] from M2_Core_SecurityPolicy where [Name]=@Name
        if (not @nameExists is null)
        begin
            raiserror (N'Name is already in use: %s',
            11,
            1,
            @Name)
        end
        else
        begin
    
            INSERT INTO M2_Core_SecurityPolicy
                ([Name],Comment)
                values
                (@Name,@Comment)
    
            IF @@ROWCOUNT > 0 
            BEGIN
                SET @id=SCOPE_IDENTITY()
                SELECT @id as ID,[Timestamp] FROM M2_Core_SecurityPolicy WHERE ID=@id
            END
    
        end
    
    go
    

    and the Mapping is changed so that it picks up the “new” field:

    Model - Mapping details

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a data structure that represents C# code like this: class Namespace: string
I have a tree data structure that is L levels deep each node has
Assuming Visual C/C++ 6, I have a complex data structure of 22399 elements that
I have to write a component that re-creates SQL Server tables (structure and data)
I have the following data structure (a list of lists) [ ['4', '21', '1',
Let's say we have a solution with the following structure: Project.DAL - Data access
Let's say I have data structures that're something like this: Public Class AttendenceRecord Public
I have the following problem in my Data Structures and Problem Solving using Java
I have a set of core, complicated JavaScript data structures/classes that I'd like to
I have this C++ code: extern C __declspec(dllexport) VOID AllocateFoo(MY_DATA_STRUCTURE** foo) { *foo =

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.