开发者

EF 4 - Exception when updating table with timestamp column

I have created the following table in SQL Server

CREATE TABLE [dbo].[Role](
   [Id] [int] IDENTITY(1,1) NOT NULL,
   [Name] [nvarchar](20) NOT NULL,
   [CreatedDate] [datetime] NULL,
   [TIMESTAMP] [timestamp] NOT NULL,
   [ModifiedDate] [datetime] NULL,

   CONSTRAINT [PK_TBL_ROLES] PRIMARY KEY CLUSTERED ([Id] ASC)
       WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, 
             AL开发者_StackOverflow中文版LOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY].

With EF, I created a ste class with timestamp column of type byte[] which is readonly.

I retrieve an object from my db using the datacontext e.g.

var roleObject = roleService.getObject(id);

now I change the rolename as follows

roleObject.Name = "New Name";
roleObject.ModifiedDate = DateTime.Now;

finally I call my repository to persist the object using the following generic method

public void PersistUpdatedItem(T entity){
   _ctx.ApplyCurrentValues(typeof (T).Name, entity);
   _ctx.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
   _ctx.SaveChanges();
}

Note ctx is my session object and T is the entity class. At this point I get an exception

Cannot update Timestamp Column

Can someone please assist me in solving this one.

thanks


Two points:

  • You cannot make Timestamp property "read only". EF must be able to set that value so the property must have setter and accessibility of the setter must be same as accessibility defined in the designer.
  • Your Timestamp property must be configured with Concurrency Mode Fixed and StoreGenerated Pattern Coumputed. Both these configurations are defined in properties window in the designer.


Just remove the timestamp from your model object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜